﻿/*
 Copyright (c) 2010, Igor L. B.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the iglaweb nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Igor L. B. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

//Notifications and hibernate...
using Microsoft.WindowsCE.Forms;

// Cookie (not in CF), HTTPRequest, HTTPResponse
using System.Net;

//WinApi
using System.Runtime.InteropServices;

// Streams
using System.IO;

//Security
using System.Security.Cryptography;

//Regular expressions
using System.Text.RegularExpressions;

//Streams
using System.Threading;

using System.Reflection;

//lib for Gzip compression/decompression
using ICSharpCode.SharpZipLib.GZip;

namespace BeOnline
{
    public partial class Main_Form : Form
    {
        private NotifyClient.NotifyIcon notifyIcon;
        private System.Windows.Forms.Timer timer;
                
        public void Orientation()
        {
            this.label_stats_info.Width = Screen.PrimaryScreen.WorkingArea.Width;
            this.listBox_friends_list.Width = Screen.PrimaryScreen.WorkingArea.Width;
        }

        public Image leftarrow = global::BeOnline.Properties.Resources.leftarrow;
        public Image rightarrow = global::BeOnline.Properties.Resources.rigtharrow;

        public Main_Form()
        {
            InitializeComponent();

            notifyIcon = new NotifyClient.NotifyIcon();
            notifyIcon.Click += new EventHandler(notifyIcon_Click);

            Orientation();
            Stats();
            TrafficReceived = 0;
            TrafficSended = 0;
        }
       

        #region API
        
        #region Минимизация окна

        private void MinimizeButton_Click()
        {
            ShowWindow(this.Handle, SHOWWINDOW.SW_MINIMIZE);
        }

        private void ShowButton_Click()
        {
            ShowWindow(this.Handle, SHOWWINDOW.SW_SHOW);
        }

        public enum SHOWWINDOW : uint
        {
            SW_SHOW = 5,
            SW_MINIMIZE = 6,
            SW_RESTORE = 9
        }

        [DllImport("coredll.dll")]
        internal static extern int ShowWindow(IntPtr hwnd, SHOWWINDOW cmdShow);
        #endregion

        #region Звук
        public class Sound
        {
            private byte[] m_soundBytes;
            private string m_fileName;

            private enum Flags
            {
                SND_SYNC = 0x0000,  /* play synchronously (default) */
                SND_ASYNC = 0x0001,  /* play asynchronously */
                SND_NODEFAULT = 0x0002,  /* silence (!default) if sound not found */
                SND_MEMORY = 0x0004,  /* pszSound points to a memory file */
                SND_LOOP = 0x0008,  /* loop the sound until next sndPlaySound */
                SND_NOSTOP = 0x0010,  /* don't stop any currently playing sound */
                SND_NOWAIT = 0x00002000, /* don't wait if the driver is busy */
                SND_ALIAS = 0x00010000, /* name is a registry alias */
                SND_ALIAS_ID = 0x00110000, /* alias is a predefined ID */
                SND_FILENAME = 0x00020000, /* name is file name */
                SND_RESOURCE = 0x00040004  /* name is resource name or atom */
            }

            [DllImport("CoreDll.DLL", EntryPoint = "PlaySound", SetLastError = true)]
            private extern static int WCE_PlaySound(string szSound, IntPtr hMod, int flags);

            [DllImport("CoreDll.DLL", EntryPoint = "PlaySound", SetLastError = true)]
            private extern static int WCE_PlaySoundBytes(byte[] szSound, IntPtr hMod, int flags);

            /// <summary>
            /// Construct the Sound object to play sound data from the specified file.
            /// </summary>
            public Sound(string fileName)
            {
                m_fileName = fileName;
            }

            /// <summary>
            /// Construct the Sound object to play sound data from the specified stream.
            /// </summary>
            public Sound(Stream stream)
            {
                // read the data from the stream
                m_soundBytes = new byte[stream.Length];
                stream.Read(m_soundBytes, 0, (int)stream.Length);
            }

            /// <summary>
            /// Play the sound
            /// </summary>
            public void Play()
            {
                // if a file name has been registered, call WCE_PlaySound,
                //  otherwise call WCE_PlaySoundBytes
                if (m_fileName != null)
                    WCE_PlaySound(m_fileName, IntPtr.Zero, (int)(Flags.SND_SYNC | Flags.SND_FILENAME));
                else
                    WCE_PlaySoundBytes(m_soundBytes, IntPtr.Zero, (int)(Flags.SND_ASYNC | Flags.SND_MEMORY));
            }
        }
        #endregion

        #region Нотифы
        public class Notification
        {
            [DllImport("notification.dll")]
            public static extern int AddEventNotification(NotificationEventEnum notificationEvent, string applicationPath, string arguments);

            [DllImport("notification.dll")]
            public static extern int RemoveAppNotifications(NotificationEventEnum notivicationEvent, string applicationPath);

            [DllImport("notification.dll")]
            public static extern int IsEventNotificationExists(NotificationEventEnum notivicationEvent, string applicationPath, out IntPtr phNotify);
        }

        public enum NotificationEventEnum
        {
            None = 0,                    //#define NOTIFICATION_EVENT_NONE                 0
            TimeChange = 1,                //#define NOTIFICATION_EVENT_TIME_CHANGE          1
            SyncEnd = 2,                //#define NOTIFICATION_EVENT_SYNC_END             2
            OnAcPower = 3,                //#define NOTIFICATION_EVENT_ON_AC_POWER          3
            OffAcPower = 4,                //#define NOTIFICATION_EVENT_OFF_AC_POWER         4
            NetConnect = 5,                //#define NOTIFICATION_EVENT_NET_CONNECT          5
            NetDisconnect = 6,            //#define NOTIFICATION_EVENT_NET_DISCONNECT       6
            DeviceChange = 7,            //#define NOTIFICATION_EVENT_DEVICE_CHANGE        7
            IrDiscovered = 8,            //#define NOTIFICATION_EVENT_IR_DISCOVERED        8
            RS232Detected = 9,            //#define NOTIFICATION_EVENT_RS232_DETECTED       9
            RestoreEnd = 10,            //#define NOTIFICATION_EVENT_RESTORE_END         10
            WakeUp = 11,                //#define NOTIFICATION_EVENT_WAKEUP              11
            TimeZoneChange = 12,        //#define NOTIFICATION_EVENT_TZ_CHANGE           12
            MachineNameChange = 13,        //#define NOTIFICATION_EVENT_MACHINE_NAME_CHANGE 13
            EventLast = MachineNameChange//#define NOTIFICATION_EVENT_LAST                NOTIFICATION_EVENT_MACHINE_NAME_CHANGE
        };

        #endregion

        #region Клавиатура
        private const uint SIPF_OFF = 0x0;
        private const uint SIPF_ON = 0x1;
       
        [DllImport("coredll.dll")]
        private extern static void SipShowIM(uint dwFlag);
        #endregion

        #region Иконка в трее
        [DllImport("coredll.dll")]
        internal static extern IntPtr LoadIcon(IntPtr hInst, string IconName);
        
        [DllImport("coredll.dll")]
        internal static extern IntPtr GetModuleHandle(String lpModuleName);
        #endregion

        #region Нотификации

       
        


        #endregion

        #region Вибрация
       
        /// <summary>
        /// Включает виброзвонок
        /// </summary>
        [DllImport("aygshell.dll")]
        private static extern int Vibrate(
            int cvn,
            IntPtr rgvn,
            uint fRepeat,
            uint dwTimeout);
       
        /// <summary>
        /// Останавливает виброзвонок
        /// </summary>
        [DllImport("aygshell.dll")]
        private static extern int VibrateStop();


        #endregion

        #endregion

        private void Stats()
        {
            DateTime date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            label_stats_info.Text = date.ToString("g") + " || ";
        }

        #region константы и переменные
        /// <summary>
        ///     URL сайта
        /// </summary>
        private const string site_url = "http://vkontakte.ru/";
        /// <summary>
        ///     HOST
        /// </summary>
        private const string site_host = "vkontakte.ru";
        /// <summary>
        ///     Кодировка страниц
        /// </summary>
        private System.Text.Encoding site_encoding = System.Text.Encoding.GetEncoding(1251);
        /// <summary>
        ///     БД
        /// </summary>

        public static string path_to_settings = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\settings.txt";

        public const string password_db = "";

        public static string exception = "";//Обработка исключений

        //Трафик
        public static long traffic_bytes = 0;

        public long TrafficReceived { get; set; }
        public long TrafficSended { get; set; }


        public const int site_id = 2;

        public const int max_friends = 2500;
        public const int max_friends_online = 2500;
        public const int max_friends_mutual = 2500; //Список общих друзей с пользователем
        public const int max_friends_new = 2500; //Список подавших заявки в друзья текущему пользователю

        public const int max_status_history = 15; //История статуса

        public const int max_messages_in = 20;
        public const int max_messages_out = 20;
        public const int max_messages_current_user = 20;
        
        #endregion

        /*Structures*/
      
        /// <summary>
        ///   Классы для промежуточных действий с сообщениями
        /// </summary>
        struct Messages_detail
        {
            public class m_in
            {
                public m_in() { }
                public static string message_id;
                public static string sender_id;
                public static string message_topic;
                public static string message;
            }
            public class m_out
            {
                public m_out() { }
                public static string message_id;
                public static string sender_id;
                public static string message_topic;
                public static string message;
            }
        }
        
        /*Classes*/

        public class Threads
        {
            public static Thread main_thread;
            public static Thread dissconnect_thread;
            public static Thread settings_thread;
            public static Thread friends_thread;
            public static Thread status_thread;
            public static Thread settings_change_name_thread;
            public static Thread messages_thread;
            public static Thread wall_messages;
            public static Thread notification;
        }

        public class Main_Friends
        {
            //Common for friends
            public static string[] id;
            public static string[] name;
            public static string[] surname;
            public static string[] year;
            public static string[] avatar;
            public static string[] codeinstitute;
            public static string[] whom;
            public static string[] faculty;

            //University
            public static string[] id_inst;
            public static string[] name_inst;
            public static string[] id_fac;
            public static string[] name_fac;

            public static string NAME_to_send_message;
            public static bool Send_message;

            public static bool Save_profile;
            public static string NAME_to_save_profile;
            public Main_Friends()
            {
                Send_message = false;
                NAME_to_send_message = "";
            }
        }

        public class Main_Settings_API
        {
            public static string[] theme = new string[0];
            public static string[] parameter = new string[0];
            public static string[] value = new string[0];
        }

        public class Main_Friends_API
        {
            public static string[] id;
            public static string[] name;
            public static string[] url_avatar;
            public static bool[] status;
            public static int friend_list_index;
        }

        struct Messages_API
        {
            public static int messages_list_index;
            public class in_m
            {
                public static string[] id_message = new string[max_messages_in];
                public static string[] unixtime = new string[max_messages_in];
                public static string[] message = new string[max_messages_in];
                public static string[] sender_id = new string[max_messages_in];
                public static string[] read = new string[max_messages_in];
                public static string[] user_id = new string[max_messages_in];
                public static string[] user_name = new string[max_messages_in];
                public static string[] user_avatar = new string[max_messages_in];
                public static string[] user_avatar_small = new string[max_messages_in];
                public static string[] user_sex = new string[max_messages_in];
                public static string[] user_status = new string[max_messages_in];
            }

            public class out_m
            {
                public static string[] id_message = new string[max_messages_out];
                public static string[] unixtime = new string[max_messages_out];
                public static string[] message = new string[max_messages_out];
                public static string[] sender_id = new string[max_messages_out];
                public static string[] read = new string[max_messages_out];
                public static string[] user_id = new string[max_messages_out];
                public static string[] user_name = new string[max_messages_out];
                public static string[] user_avatar = new string[max_messages_out];
                public static string[] user_avatar_small = new string[max_messages_out];
                public static string[] user_sex = new string[max_messages_out];
                public static string[] user_status = new string[max_messages_out];
            }
        }

        public class Main_History_Status_API
        {
            public static string[] iduser_idstatus;
            public static string[] id;
            public static string[] num;
            public static string[] name;
            public static string[] unixtime;
            public static string[] text;
        }

        public class Main_Traffic_API
        {
            public static long ingoing = 0;
            public static long outgoing = 0;
        }

        public class Main_Menuitems
        {
            public static byte tag = 2;//Список друзей при загрузке формы
            public static MenuItem[] friends;
            public static MenuItem[] friends_online;
            public static MenuItem[] friends_mutual;
            public static MenuItem[] friends_new;
            public static MenuItem[] friends_send_message;
            public static MenuItem[] status;
            public static MenuItem[] messages_in;
            public static MenuItem[] messages_out;
            public static MenuItem[] messages_send_message;
            public static MenuItem[] messages_reply_message;
            public static MenuItem[] messages_new_message;
            public static MenuItem[] mypage_wall;
            public static MenuItem[] mypage_edit;
            public static MenuItem[] settings_common;
        }
        
        public class Main_Profile
        {
            //Common for profile
            public static string ID;
            public static string password;
            public static string sid;
            public static string name_profile;
            public static string sEmail;
            public static string sPassword;
            public static string sCookies;
            public static bool save_cookie;
            public static bool save_password;
            public static bool connect_on_launch;
            public static string proxy;

            public Main_Profile()
            {

            }
        }
        
        public class Main_Messages
        {
            public static string[] message_id;
            public static string[] message_topic;
            public static string[] message_this;
            public static string[] message_sender_name;
            public static string[] message_sender_id;
            public static string[] message_date;
            public static string[] message_avatar;

            public static string[] message_id_out;
            public static string[] message_topic_out;
            public static string[] message_this_out;
            public static string[] message_sender_name_out;
            public static string[] message_sender_id_out;
            public static string[] message_date_out;
            public static string[] message_avatar_out;

            public Main_Messages()
            {

            }
        }

        public class Send_message
        {
            public static string reply_message_id;
            public static string reply_sender_id;
            public static string reply_message_topic;
            public static string reply_message_body;

            public static string reply_message_id_out;
            public static string reply_sender_id_out;
            public static string reply_message_topic_out;
            public static string reply_message_body_out;

            public static bool send_message;
            public static bool outbox;//Чтобы определить посылается ли это сообщени из полученных или отправленных

            public static string[] new_message_friendslist_name;//список друзей для выбора для отправки нового сообщения
            public static string[] new_message_friendslist_id;//id друзей для выбора
            public static string chascode; //Код проверки формы
            public static bool send_new_message;

            public Send_message()
            {
                send_message = false;
            }
        }

        public class Main_settings
        {
            public static string name;
            public static string surname;
            public static string nickname;
            public static string hash;
        }
       
        public class Main_Wall
        {
            public static string[] id;
            public static string[] id_message;
            public static string[] id_wall;
            public static string[] image;
            public static bool[] status;
            public static string[] name;
            public static string[] date;
            public static string[] text;
        }

        public class Main_send_message_to_friend
        {
            public static string ID;
        }

        /// <summary>
        ///     Класс исключений
        /// </summary>
        public static class MySuperExceptionHandler
        {
            public static string Handle(Exception e)
            {
                try
                {
                    throw e;
                }
                catch (WebException ex)
                { exception = "Невозможно подключиться к сети. \nКод состояния:" + ex.Status; }
                catch (ProtocolViolationException ex)
                { exception = "Ошибка сетевого протокола" + ex.Message; }
                catch (UriFormatException ex)
                { exception = "Ошибка в формате URI:" + ex.Message; }
                catch (NotSupportedException ex)
                { exception = "Неизвестный протокол:" + ex.Message; }
                catch (IOException ex)
                { exception = "Файловая ошибка:" + ex.Message; }
                catch (ObjectDisposedException ex)
                { exception = "Операция над удаленным объектом:" + ex.Message; }
                catch (NullReferenceException ex)
                { exception = "Разыименование указателя null на объект:" + ex.Message; }
                catch (ArgumentOutOfRangeException ex)
                { exception = "Аргумент вне допустимого диапозона значений:" + ex.Message; }
                catch (CryptographicException ex)
                { exception = "Ошибка при выполнении криптографической операции:" + ex.Message; }
                catch (Exception ex)
                { exception = ex.Message; }
                return exception;
            }
        }

        /// <summary>
        ///     Класс шифрования/дешифрования
        /// </summary>
        public class Rijndael_Algorithm
        {
            public static string Encrypt(string Data)
            {
                //Заданный ключ Key: длина ключа 256bit (32 bytes)
                byte[] Key = new byte[] { 194, 61, 213, 244, 141, 188, 172, 76, 251, 99, 252, 139, 89, 2, 205, 240, 27, 216, 181, 245, 240, 171, 239, 113, 22, 234, 66, 87, 246, 100, 87, 214 };
                //Вектор инициализации: 128bit(16 bytes)
                byte[] IV = new byte[] { 149, 7, 196, 206, 172, 5, 33, 229, 55, 242, 113, 7, 75, 72, 170, 149 };

                string output = "";

                if (!String.IsNullOrEmpty(Data.Trim()))
                {
                    Data = Data.Trim();
                    // Создаем симметричный алгоритм шифрования Rjindael, как надежного и доступного на всех платформах.
                    Rijndael RijndaelAlg = Rijndael.Create();

                    //Переводим в последовательность байтов, используя кодировку Unicode
                    byte[] b = System.Text.Encoding.Unicode.GetBytes(Data);

                    //Создаем поток для записи
                    MemoryStream mem = new MemoryStream();


                    // Создаем объект CryptoStream используя заданный ключ и вектор инициализации (IV).
                    CryptoStream cStream = new CryptoStream(mem,RijndaelAlg.CreateEncryptor(Key,IV),CryptoStreamMode.Write);

                        //Записываем последовательность байтов в поток
                        cStream.Write(b, 0, b.Length);
                       
                        //Закрываем потоки и освобождаем реусры
                        cStream.Close();
                        mem.Close();
                        RijndaelAlg.Clear();


                    //Base64 кодировка
                    byte[] Encrypted = mem.ToArray();
                    output = Convert.ToBase64String(Encrypted);
                }
                return output;
            }
            public static string Decrypt(string Data)
            {
                byte[] Key = new byte[] { 194, 61, 213, 244, 141, 188, 172, 76, 251, 99, 252, 139, 89, 2, 205, 240, 27, 216, 181, 245, 240, 171, 239, 113, 22, 234, 66, 87, 246, 100, 87, 214 };
                byte[] IV = new byte[] { 149, 7, 196, 206, 172, 5, 33, 229, 55, 242, 113, 7, 75, 72, 170, 149 };

                string output = "";
                if (!String.IsNullOrEmpty(Data.Trim()))
                {
                    Data = Data.Trim();
                    byte[] b = Convert.FromBase64String(Data);
                     
                    Rijndael RijndaelAlg = Rijndael.Create();
                    
                    MemoryStream mem = new MemoryStream();

                    CryptoStream cStream = new CryptoStream(mem, RijndaelAlg.CreateDecryptor(Key,IV), CryptoStreamMode.Write);

                    cStream.Write(b, 0, b.Length);

                        //Закрываем потоки и освобождаем ресурсы
                        cStream.Close();
                        mem.Close();
                        RijndaelAlg.Clear();

                    byte[] Decrypted = mem.ToArray();
                    output = System.Text.Encoding.Unicode.GetString(Decrypted, 0, Decrypted.Length);
                }
                return output;
            }
        }

        /// <summary>
        ///     Класс Gzip распаковки/упаковки
        /// </summary>
        /// 
        public class GzipCompress
        {
            public static string DeCompressGzip(string str)
            {

                MemoryStream compressedStream = new MemoryStream();

                byte[] compressedBytes = Encoding.GetEncoding(1251).GetBytes(str);

                compressedStream = new MemoryStream(compressedBytes);

                MemoryStream targetStream = new MemoryStream();
                using (GZipInputStream inStream = new GZipInputStream(compressedStream))
                {
                    byte[] buffer = new byte[2048];
                    int bytesRead;
                    while ((bytesRead = inStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        targetStream.Write(buffer, 0, bytesRead);
                    }
                }

                str = Encoding.GetEncoding(1251).GetString(targetStream.ToArray(), 0, Convert.ToInt32(targetStream.Length));

                //Закрываем потоки распаковки
                compressedStream.Close();
                targetStream.Close();
                return str;
            }
            public static string EnCompressGzip(string str)
            {

                byte[] srcBytes = Encoding.GetEncoding(1251).GetBytes(str);

                MemoryStream compressedStream = new MemoryStream();
                using (GZipOutputStream outStream = new GZipOutputStream(compressedStream))
                {
                    outStream.Write(srcBytes, 0, srcBytes.Length);
                }
                byte[] compressedBytes = compressedStream.ToArray();

                str = Encoding.GetEncoding(1251).GetString(compressedBytes, 0, compressedBytes.Length);

                //Закрывем потоки упаковки
                compressedStream.Close();

                return str;
            }
        }

        /// <summary>
        ///     Основной класс движка программы
        /// </summary>
        public class howitworks
        {
            public static string resultoutput;
            public static bool auth_status;
            public static int numberfriends;
            public static int numberunivs;
            public static int numberfacs;
            public static int numbermessages;
            public static int wallnumbermessages;
            public static int id;

            //Для поочередной смены картинки
            public static bool show_picture = true;

            //Для счетчика нажиманий картинки
            public static int counter = 0;

            //Для таймера
            public static int cx;
            public static int cy;

            //Двойная буферизация
            public static Bitmap backBuffer = null;

            public howitworks()
            {
                cx = 0;
                cy = 0;
                resultoutput = "";
                auth_status = false;
            }
        }

        /// <summary>
        /// Класс для скрытия/отображения всех Panel
        /// </summary>
        public class Manage_Panels
        {
            public void HideControls(Control.ControlCollection controls)
            {
                for (int i = 0; i < controls.Count; i++)
                {
                    if (controls[i] is Panel)
                        (controls[i] as Panel).Hide();
                }
            }
            public void ShowControls(Control.ControlCollection controls)
            {
                for (int i = 0; i < controls.Count; i++)
                {
                    if (controls[i] is Panel)
                        (controls[i] as Panel).Show();
                }
            }
        }

        /// <summary>
        /// Класс для для поточности списка друзей
        /// </summary>

        public class ThreadFriends_list_api
        {
            private string url;

            Main_Form form;
            public ThreadFriends_list_api(string text, Main_Form parent)
            {
                url = text;
                form = parent;
            }

            public void go()
            {
                form.Friends_userapi(url);
            }
        }

        public class ThreadMessages_list_api
        {
            private string url;

            Main_Form form;
            public ThreadMessages_list_api(string text, Main_Form parent)
            {
                url = text;
                form = parent;
            }

            public void go()
            {
                form.Messages_userapi(url);
            }
        }

        public class ThreadFriends_send_message_api
        { 
          private string id;
          private string message;
          private string act;

            Main_Form form;
            public ThreadFriends_send_message_api(string id_user, string msg, string action, Main_Form parent)
            {
                id = id_user;
                message = msg;
                act = action;

                form = parent;
            }

            public void go()
            {
                form.Send_message_userapi(id, message, act);
            }
        }

        public class ThreadFriends_set_status_api
        {
            private string status;

            Main_Form form;
            public ThreadFriends_set_status_api(string set_status, Main_Form parent)
            {
                status = set_status;

                form = parent;
            }

            public void go()
            {
                form.Set_status_userapi(status);
            }
        }
        
        /// <summary>
        /// Класс для для многопоточности списка сообщений со стены
        /// </summary>

        public class Thread_delete_message
        {
            private string act;

            Main_Form form;
            public Thread_delete_message(string text, Main_Form parent)
            {
                act = text;
                form = parent;
            }

            public void go()
            {
                form.Messages_delete_userapi(act);
            }
        }

        /******Методы******/

        /// <summary>
        ///     Метод обновления строки состояния
        /// </summary>
        public void AddToLog(string Msg, bool onscreen)
        {
            if (onscreen)
            {
                statusBar_status.Invoke(new EventHandler(delegate { statusBar_status.Text = Msg; statusBar_status.Refresh(); }));
            };
        }


        /*Vkontakte UserApi.com*/

        public void Auth_userapi()
        {
            //Get
            /*Авторизация*/ 
            if (!string.IsNullOrEmpty(Main_Profile.sEmail) && !string.IsNullOrEmpty(Main_Profile.sPassword))
                try
                {
                    string sCookies = "";
                    AddToLog("Составление запроса", true);
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://login.userapi.com/auth?login=force&site=" + site_id.ToString() + "&email=" + Main_Profile.sEmail.ToString() + "&pass=" + (Rijndael_Algorithm.Decrypt(Main_Profile.sPassword)).ToString());
                    myHttpWebRequest.Method = "GET";
                    myHttpWebRequest.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                    myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                    myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                    myHttpWebRequest.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                    myHttpWebRequest.KeepAlive = true;
                    myHttpWebRequest.Headers["Accept-Encoding"] = "gzip";
                    myHttpWebRequest.AllowAutoRedirect = false;

                    AddToLog("Отправка запроса", true);
                    // делаем запрос
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                    //Трафик
                    TrafficReceived += myHttpWebResponse.ContentLength;
                    label_stats_trafic.Invoke(new EventHandler(delegate { label_stats_trafic.Text = Methods.CountTraffic(TrafficReceived); })); 

                    if (!String.IsNullOrEmpty(myHttpWebResponse.Headers["Set-Cookie"]))
                    {
                        sCookies = myHttpWebResponse.Headers["Set-Cookie"];
                    }

                    string sLocation = myHttpWebResponse.Headers["Location"];//узнаем страницу на которую редирект

                    //Закрываем потоки
                    myHttpWebResponse.Close();

                    if (sLocation != null)
                    {
                        Regex r_sid = new Regex("sid=(?<sid>.+)");
                        Match m_sid = r_sid.Match(sLocation);
                        /*id*/
                        Regex r_id = new Regex("remixmid=(?<id>\\d+)[;]");
                        Match m_id = r_id.Match(sCookies);

                        /*password*/
                        Regex r_pass = new Regex("remixpassword=(?<password>\\d+)[;]");
                        Match m_pass = r_pass.Match(sCookies);

                        string sid = (m_sid.Success) ? m_sid.Groups["sid"].Value : "";

                        if (sid == "-1")
                        {
                            AddToLog("Авторизоваться не удалось: " + sid, true);
                        }
                        else if (sid == "-2")
                        {
                            AddToLog("Неверно введена captcha при отсылке email и пароля", true);
                        }
                        else if (sid == "-3")
                        {
                            AddToLog("Неверный email или пароль, при следующей попытке нужно ввести captcha", true);
                        }
                        else if (sid == "-4")
                        {
                            AddToLog("Неверный email или пароль, captcha не нужна", true);
                        }
                        else
                        {
                            howitworks.auth_status = true;
                            Main_Profile.sid = sid;
                            Main_Profile.ID = m_id.Groups["id"].Value;
                            Main_Profile.password = m_pass.Groups["password"].Value;
                            panel1_send_message_tofriend.Invoke(new EventHandler(delegate { menuItem_auth.Text = (howitworks.auth_status == true) ? "Отключиться" : "Подключиться"; })); 
                            AddToLog("Вы успешно авторизованы", true);
                        }
                    }
                    else
                    {
                        AddToLog("Редирект равен null", true);
                    }

                }
                catch (Exception e)
                {
                    statusBar_status.Text = MySuperExceptionHandler.Handle(e);
                }
            else
            {
                AddToLog("Поля Email/Пароль не заполнены", true);
            }
        }

        public void Logout_userapi()
        {
            /*Авторизация*/
            AddToLog("Составление запроса", true);
            try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://login.userapi.com/auth?login=logout&site=" + site_id.ToString() + "&sid=" + Main_Profile.sid);
                myHttpWebRequest.Method = "GET";
                myHttpWebRequest.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                myHttpWebRequest.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                myHttpWebRequest.KeepAlive = true;
                myHttpWebRequest.Headers["Accept-Encoding"] = "gzip";
                myHttpWebRequest.AllowAutoRedirect = false;

                AddToLog("Отправка запроса", true);
                // делаем запрос
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                //Трафик
                TrafficReceived += myHttpWebResponse.ContentLength;
                label_stats_trafic.Invoke(new EventHandler(delegate { label_stats_trafic.Text = Methods.CountTraffic(TrafficReceived); })); 

                string sLocation = myHttpWebResponse.Headers["Location"];//узнаем страницу на которую редирект

                //Закрываем потоки
                myHttpWebResponse.Close();


                if (sLocation.IndexOf("/index.html", 0) == -1)
                {
                    AddToLog("Выйти не удалось", true);
                }
                else
                {
                    howitworks.auth_status = false;
                    panel1_send_message_tofriend.Invoke(new EventHandler(delegate { menuItem_auth.Text = (howitworks.auth_status == true) ? "Отключиться" : "Подключиться"; })); 
                    AddToLog("Вы успешно стерли сессию", true);
                }
            }
            catch (Exception e)
            {
                statusBar_status.Text = MySuperExceptionHandler.Handle(e);
            }
        }

        public void Friends_userapi(string act)  
        {
            if (howitworks.auth_status == false)
                AddToLog("Вы не авторизованы.", true);
            else
                try
                {
                    int num = 1000;
                    if (act == "friends_mutual")
                    {
                        num = max_friends_mutual;
                    }
                    else if (act == "friends_online")
                    {
                        num = max_friends_online;
                    }
                    else if (act == "friends_new")
                    {
                        num = max_friends_new;
                    }
                    else
                    {
                        num = max_friends;
                        act = "friends";
                    }

                    AddToLog("Составление запроса", true);
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://userapi.com/data?act=" + act + "&from=0&to=" + num.ToString() + "&id=" + Main_Profile.ID + "&sid=" +  Main_Profile.sid);
                    myHttpWebRequest.Method = "GET";
                    myHttpWebRequest.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                    myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                    myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                    myHttpWebRequest.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                    myHttpWebRequest.KeepAlive = true;
                    myHttpWebRequest.Headers.Add("Cache-Control", "no-cache");
                    myHttpWebRequest.AllowAutoRedirect = false;

                    AddToLog("Выполнение запроса", true);
                    // делаем запрос
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                    //Трафик
                    TrafficReceived += myHttpWebResponse.ContentLength;
                    label_stats_trafic.Invoke(new EventHandler(delegate { label_stats_trafic.Text = Methods.CountTraffic(TrafficReceived); })); 


                    string sLocation = myHttpWebResponse.Headers["Location"];//узнаем страницу на которую редирект

                    Stream messagepage = myHttpWebResponse.GetResponseStream();

                    StreamReader messagepage_reader = new StreamReader(messagepage, Encoding.UTF8);

                    string str = messagepage_reader.ReadToEnd();//Получаем всю страницу

                    //Закрываем потоки
                    myHttpWebResponse.Close();

                    string[,] json_mass = (string[,])Methods.JsonParser(str, false);

                    if (json_mass.Length > 0)
                    {
                        for (int i = 0; i < json_mass.GetLength(0); i++)
                        {
                            listBox_friends_list.Invoke(new EventHandler(delegate { listBox_friends_list.Items.Add(json_mass[i, 1]); }));
                        }

                        listBox_friends_list.Invoke(new EventHandler(delegate { listBox_friends_list.Focus(); listBox_friends_list.SelectedIndex = 0; }));
                        AddToLog("Список друзей успешно загружен", true);
                    }
                    else
                    {
                        if (act == "friends_mutual")
                        {
                            AddToLog("Список общих друзей пуст", true);
                        }
                        else if (act == "friends_online")
                        {
                            AddToLog("Список онлайн друзей пуст", true);
                        }
                        else if (act == "friends_new")
                        {
                            AddToLog("Нет заявок на доблавления в друзья", true);
                        }
                        else
                        {
                            AddToLog("Список друзей пуст", true);
                        }
                    }
                }
                catch (Exception e)
                {
                    statusBar_status.Text = MySuperExceptionHandler.Handle(e);
                }
        }

        public void Friends_userapi_test(string act)
        {
            if (howitworks.auth_status == false)
                AddToLog("Вы не авторизованы.", true);
            else
                try
                {
                    //Обнуляем массивы
                    Main_Friends_API.id = new string[0];
                    Main_Friends_API.name = new string[0];
                    Main_Friends_API.url_avatar = new string[0];
                    Main_Friends_API.status = new bool[0];


                    int num = 1000;
                    if (act == "friends_mutual")
                    {
                        num = max_friends_mutual;
                    }
                    else if (act == "friends_online")
                    {
                        num = max_friends_online;
                    }
                    else if (act == "friends_new")
                    {
                        num = max_friends_new;
                    }
                    else
                    {
                        num = max_friends;
                        act = "friends";
                    }

                    Array test;

                    AddToLog("Составление запроса", true);
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://userapi.com/data?act=" + act + "&from=0&to=" + num.ToString() + "&id=" + Main_Profile.ID + "&sid=" + Main_Profile.sid);
                    myHttpWebRequest.Method = "GET";
                    myHttpWebRequest.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                    myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                    myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                    myHttpWebRequest.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                    myHttpWebRequest.KeepAlive = true;
                    myHttpWebRequest.Headers.Add("Cache-Control", "no-cache");
                    myHttpWebRequest.AllowAutoRedirect = false;

                    AddToLog("Выполнение запроса", true);
                    // делаем запрос
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                    string sLocation = myHttpWebResponse.Headers["Location"];//узнаем страницу на которую редирект

                    Stream messagepage = myHttpWebResponse.GetResponseStream();

                    StreamReader messagepage_reader = new StreamReader(messagepage, Encoding.UTF8);

                    string str = messagepage_reader.ReadToEnd();//Получаем всю страницу

                    //Закрываем потоки
                    myHttpWebResponse.Close();

                    test = Methods.JsonParser(str, false);

                    //Обрабатываем json массив

                    Regex r_history_json = new Regex("[[[](?<friends>.+)[]]");
                    Match m_history_json = r_history_json.Match(str);

                    str = (m_history_json.Success) ? m_history_json.Groups["friends"].Value : "";

                    int found_start = str.IndexOf("[");
                    int found_end = str.IndexOf("]", found_start);

                    string[,] friends = new string[4, num];
                    int numberfriends = 0;
                    string part;

                    while (found_start != -1 && found_end != -1)
                    {
                        part = str.Substring(found_start, found_end - found_start);

                        Regex r_part = new Regex("(?<id>\\d+),\"(?<name>.+)\",\"(?<photo>.+)\",(?<status>\\d+)");
                        Match m_part = r_part.Match(part, found_start, found_end - found_start);

                        friends[0, numberfriends] = m_part.Groups["id"].Value;
                        friends[1, numberfriends] = m_part.Groups["name"].Value;
                        friends[2, numberfriends] = m_part.Groups["photo"].Value;
                        friends[3, numberfriends] = m_part.Groups["status"].Value;

                        Main_Friends_API.id = (string[])Methods.IncreaseArray(Main_Friends_API.id, numberfriends + 1);
                        Main_Friends_API.name = (string[])Methods.IncreaseArray(Main_Friends_API.name, numberfriends + 1);
                        Main_Friends_API.url_avatar = (string[])Methods.IncreaseArray(Main_Friends_API.url_avatar, numberfriends + 1);
                        Main_Friends_API.status = (bool[])Methods.IncreaseArray(Main_Friends_API.status, numberfriends + 1);

                        Main_Friends_API.id[numberfriends] = friends[0, numberfriends];
                        Main_Friends_API.name[numberfriends] = friends[1, numberfriends];
                        Main_Friends_API.url_avatar[numberfriends] = friends[2, numberfriends];
                        Main_Friends_API.status[numberfriends] = (friends[3, numberfriends] == "1") ? true : false;

                        part += "]";

                        found_start = str.IndexOf("[", found_end);

                        if (found_start != -1)
                        { part += ","; }

                        str = str.Replace(part, "");

                        found_start = str.IndexOf("[");
                        found_end = str.IndexOf("]", found_start);

                        numberfriends++;
                    }

                    //Добавляем в listbox


                    if (numberfriends > 0)
                    {
                        listBox_friends_list.Invoke(new EventHandler(delegate { listBox_friends_list.Items.Clear(); }));
                        for (int i = 0; i < numberfriends; i++)
                        {
                            listBox_friends_list.Invoke(new EventHandler(delegate { listBox_friends_list.Items.Add(friends[1, i]); }));
                        }
                        listBox_friends_list.Invoke(new EventHandler(delegate { listBox_friends_list.Focus(); listBox_friends_list.SelectedIndex = 0; }));


                        AddToLog("Список друзей успешно загружен", true);
                    }
                    else
                    {
                        if (act == "friends_mutual")
                        {
                            AddToLog("Список общих друзей пуст", true);
                        }
                        else if (act == "friends_online")
                        {
                            AddToLog("Список онлайн друзей пуст", true);
                        }
                        else if (act == "friends_new")
                        {
                            AddToLog("Нет заявок на доблавления в друзья", true);
                        }
                        else
                        {
                            AddToLog("Список друзей пуст", true);
                        }
                    }

                }
                catch (Exception e)
                {
                    statusBar_status.Text = MySuperExceptionHandler.Handle(e);
                }
        }

        public void History_status_userapi()
        {
           if (howitworks.auth_status == false)
                AddToLog("Вы не авторизованы.", true);
            else
               try
               {
                   //обнуляем массивы
                   Main_History_Status_API.id = new string[0];
                   Main_History_Status_API.iduser_idstatus = new string[0];
                   Main_History_Status_API.name = new string[0];
                   Main_History_Status_API.num = new string[0];
                   Main_History_Status_API.text = new string[0];
                   Main_History_Status_API.unixtime = new string[0];

                   AddToLog("Составление запроса", true);
                   HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://userapi.com/data?act=activity&from=0&to=" + max_status_history + "&id=" + Main_Profile.ID + "&sid=" + Main_Profile.sid);
                   myHttpWebRequest.Method = "GET";
                   myHttpWebRequest.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                   myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                   myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                   myHttpWebRequest.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                   myHttpWebRequest.KeepAlive = true;
                   myHttpWebRequest.AllowAutoRedirect = false;

                   AddToLog("Выполнение запроса", true);
                   // делаем запрос
                   HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                   //Трафик
                   TrafficReceived += myHttpWebResponse.ContentLength;
                   label_stats_trafic.Invoke(new EventHandler(delegate { label_stats_trafic.Text = Methods.CountTraffic(TrafficReceived); })); 

                   string sLocation = myHttpWebResponse.Headers["Location"];//узнаем страницу на которую редирект

                   Stream messagepage = myHttpWebResponse.GetResponseStream();
                   StreamReader messagepage_reader = new StreamReader(messagepage, Encoding.UTF8);

                   string str = messagepage_reader.ReadToEnd();//Получаем всю страницу

                   //Закрываем потоки
                   myHttpWebResponse.Close();

                   //Обрабатываем json массив

                   Regex r_history_json = new Regex("[[[](?<history>.+)[]]");
                   Match m_history_json = r_history_json.Match(str);

                   str = (m_history_json.Success) ? m_history_json.Groups["history"].Value : "";

                   int found_start = str.IndexOf("[\"");
                   int found_end = str.IndexOf("\"]", found_start);

                   string part;

                   string[,] status = new string[6, max_status_history];
                   int numberstatus = 0;

                   while (found_start != -1 && found_end != -1)
                   {
                       part = str.Substring(found_start, found_end - found_start);

                       Regex r_part = new Regex("\"(?<iduser_idstatus>.+)\",(?<id>\\d+),(?<num>\\d+),\"(?<name>.+)\",(?<unixtime>\\d+),\"(?<text>.+)");
                       Match m_part = r_part.Match(part, found_start, found_end - found_start);

                       status[0, numberstatus] = m_part.Groups["iduser_idstatus"].Value;
                       status[1, numberstatus] = m_part.Groups["id"].Value;
                       status[2, numberstatus] = m_part.Groups["num"].Value;
                       status[3, numberstatus] = m_part.Groups["name"].Value;
                       status[4, numberstatus] = m_part.Groups["unixtime"].Value;
                       status[5, numberstatus] = m_part.Groups["text"].Value;

                       Main_History_Status_API.iduser_idstatus = (string[])Methods.IncreaseArray(Main_History_Status_API.iduser_idstatus, numberstatus + 1);
                       Main_History_Status_API.id = (string[])Methods.IncreaseArray(Main_History_Status_API.id, numberstatus + 1);
                       Main_History_Status_API.num = (string[])Methods.IncreaseArray(Main_History_Status_API.num, numberstatus + 1);
                       Main_History_Status_API.name = (string[])Methods.IncreaseArray(Main_History_Status_API.name, numberstatus + 1);
                       Main_History_Status_API.unixtime = (string[])Methods.IncreaseArray(Main_History_Status_API.unixtime, numberstatus + 1);
                       Main_History_Status_API.text = (string[])Methods.IncreaseArray(Main_History_Status_API.text, numberstatus + 1);

                       Main_History_Status_API.iduser_idstatus[numberstatus] = status[0, numberstatus];
                       Main_History_Status_API.id[numberstatus] = status[1, numberstatus];
                       Main_History_Status_API.num[numberstatus] = status[2, numberstatus];
                       Main_History_Status_API.name[numberstatus] = status[3, numberstatus];
                       Main_History_Status_API.unixtime[numberstatus] = status[4, numberstatus];
                       Main_History_Status_API.text[numberstatus] = status[5, numberstatus];
                       
                       part += "\"]";

                       found_start = str.IndexOf("[\"", found_end);

                       if (found_start != -1)
                       { part += ","; }

                       str = str.Replace(part, "");

                       found_start = str.IndexOf("[\"");
                       found_end = str.IndexOf("\"]", found_start);

                       numberstatus++;
                   }

                   if (numberstatus > 0)
                   {
                       listBox_status_list.Invoke(new EventHandler(delegate { listBox_status_list.Items.Clear(); }));
                       for (int i = 0; i < numberstatus; i++)
                       {
                           listBox_status_list.Invoke(new EventHandler(delegate { listBox_status_list.Items.Add(status[5, i]); }));
                       }
                       listBox_status_list.Invoke(new EventHandler(delegate { listBox_status_list.SelectedIndex = 0; }));
                       AddToLog("Список статусов успешно загружен", true);
                   }
                   else
                   {
                       AddToLog("История статусов пуста", true);
                   }
               }
               catch (Exception e)
               {
                   statusBar_status.Text = MySuperExceptionHandler.Handle(e);
               }
        }

        public void Set_status_userapi(string status)
        {
            if (howitworks.auth_status == false)
                AddToLog("Вы не авторизованы.", true);
            else
                try
                {
                    AddToLog("Составление запроса", true);
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://userapi.com/data?act=set_activity&?id=" + Main_Profile.ID + "&wid=1_140403095&?ts=754000053&text=" + status + "&sid=" + Main_Profile.sid);
                    myHttpWebRequest.Method = "GET";
                    myHttpWebRequest.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                    myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                    myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                    myHttpWebRequest.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                    myHttpWebRequest.KeepAlive = true;
                    myHttpWebRequest.AllowAutoRedirect = false;

                    AddToLog("Выполнение запроса", true);
                    // делаем запрос
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                    //Трафик
                    TrafficReceived += myHttpWebResponse.ContentLength;
                    label_stats_trafic.Invoke(new EventHandler(delegate { label_stats_trafic.Text = Methods.CountTraffic(TrafficReceived); })); 


                    string sLocation = myHttpWebResponse.Headers["Location"];//узнаем страницу на которую редирект

                    Stream messagepage = myHttpWebResponse.GetResponseStream();
                    StreamReader messagepage_reader = new StreamReader(messagepage, Encoding.UTF8);

                    string str = messagepage_reader.ReadToEnd();//Получаем всю страницу

                    //Закрываем потоки
                    myHttpWebResponse.Close();

                    Regex r_sid = new Regex("\"ok\":(?<ok>\\d+)");
                    Match m_sid = r_sid.Match(str);

                    string ok = (m_sid.Success) ? m_sid.Groups["ok"].Value.Trim() : "";

                    if (ok == "1")
                    {
                        AddToLog("Статус успешно изменен", true);
                    }
                    else
                    {
                        AddToLog("Статус не изменен", true);
                    }
                }
                catch (Exception e)
                {
                    statusBar_status.Text = MySuperExceptionHandler.Handle(e);
                }
        }

        public void Clear_status_userapi()
        {
            if (howitworks.auth_status == false)
                AddToLog("Вы не авторизованы.", true);
            else
                try
                {
                    AddToLog("Составление запроса", true);
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://userapi.com/data?act=clear_activity&id=" + Main_Profile.ID + "&wid=1_140403095&ts=754000053&sid=" + Main_Profile.sid);
                    myHttpWebRequest.Method = "GET";
                    myHttpWebRequest.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                    myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                    myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                    myHttpWebRequest.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                    myHttpWebRequest.KeepAlive = true;
                    myHttpWebRequest.AllowAutoRedirect = false;

                    AddToLog("Выполнение запроса", true);
                    // делаем запрос
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                    //Трафик
                    TrafficReceived += myHttpWebResponse.ContentLength;
                    label_stats_trafic.Invoke(new EventHandler(delegate { label_stats_trafic.Text = Methods.CountTraffic(TrafficReceived); })); 

                    string sLocation = myHttpWebResponse.Headers["Location"];//узнаем страницу на которую редирект

                    Stream messagepage = myHttpWebResponse.GetResponseStream();
                    StreamReader messagepage_reader = new StreamReader(messagepage, Encoding.UTF8);

                    string str = messagepage_reader.ReadToEnd();//Получаем всю страницу

                    //Закрываем потоки
                    myHttpWebResponse.Close();

                    Regex r_sid = new Regex("\"ok\":(?<ok>\\d+)");
                    Match m_sid = r_sid.Match(str);

                    string ok = (m_sid.Success) ? m_sid.Groups["ok"].Value.Trim() : "";

                    if (ok == "1")
                    {
                        AddToLog("Статус успешно удален", true);
                    }
                    else
                    {
                        AddToLog("Статус не удален", true);
                    }


                }
                catch (Exception e)
                {
                    statusBar_status.Text = MySuperExceptionHandler.Handle(e);
                }
        }

        public void Send_message_userapi(string id, string message, string act)
        {
            /*act: add_wall, add_message*/
            if (howitworks.auth_status == false)
                AddToLog("Вы не авторизованы.", true);
            else
                try
                {
                    
                    message = HttpUtility.UrlEncode(message);//Декодируем
                    AddToLog("Составление запроса", true);
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://userapi.com/data?act=" + act + "&id=" + id + "&ts=64000010&message=" + message + "&sid=" + Main_Profile.sid);
                    myHttpWebRequest.Method = "GET";
                    myHttpWebRequest.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                    myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                    myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                    myHttpWebRequest.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                    myHttpWebRequest.KeepAlive = true;
                    myHttpWebRequest.AllowAutoRedirect = false;

                    AddToLog("Выполнение запроса", true);
                    // делаем запрос
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                    //Трафик
                    TrafficReceived += myHttpWebResponse.ContentLength;
                    label_stats_trafic.Invoke(new EventHandler(delegate { label_stats_trafic.Text = Methods.CountTraffic(TrafficReceived); })); 

                    Stream messagepage = myHttpWebResponse.GetResponseStream();
                    StreamReader messagepage_reader = new StreamReader(messagepage, Encoding.UTF8);

                    string str = messagepage_reader.ReadToEnd();//Получаем всю страницу

                    //Закрываем потоки
                    myHttpWebResponse.Close();

                    Regex r_sid = new Regex("\"ok\":(?<ok>\\d+)");
                    Match m_sid = r_sid.Match(str);

                    string ok = (m_sid.Success) ? m_sid.Groups["ok"].Value.Trim() : "";

                    switch (int.Parse(ok))
                    { 
                        case 1:
                            AddToLog("Сообщение успешно отправлено", true);
                            panel1_send_message_tofriend.Invoke(new EventHandler(delegate { panel1_send_message_tofriend.SendToBack(); }));
                            break;
                        case 0:
                            AddToLog("Операция прошла неуспешно", true);
                            break;
                        case -1:
                            AddToLog("Ошибка в авторизации", true);
                            break;
                        case -2:
                            AddToLog("Флуд-контроль, нужна captcha", true);
                            break;
                        case -3:
                            AddToLog("Операция запрещена приватностью", true);
                            break;
                    } 
                }
                catch (Exception e)
                {
                    statusBar_status.Text = MySuperExceptionHandler.Handle(e);
                }
        }

        public void Restore_session_userapi()
        {
            /*Авторизация*/
            AddToLog("Составление запроса", true);
            try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://login.userapi.com/auth?login=auto&site=" + site_id.ToString());
                myHttpWebRequest.Method = "GET";
                myHttpWebRequest.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                myHttpWebRequest.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                myHttpWebRequest.KeepAlive = true;
                myHttpWebRequest.Headers["Accept-Encoding"] = "gzip";
                myHttpWebRequest.Headers["Cookie"] = "remixmid=" + Main_Profile.ID + "; remixpassword=" + Main_Profile.password;
                myHttpWebRequest.AllowAutoRedirect = false;

                AddToLog("Отправка запроса", true);
                // делаем запрос
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                string sLocation = myHttpWebResponse.Headers["Location"];//узнаем страницу на которую редирект

                //Закрываем потоки
                myHttpWebResponse.Close();


                Regex r_sid = new Regex("sid=(?<sid>.+)");
                Match m_sid = r_sid.Match(sLocation);

                string sid = (m_sid.Success) ? m_sid.Groups["sid"].Value : "";

                if (sid == "-1")
                {
                    AddToLog("Не удалось продлить сессию", true);
                }
                else
                {
                    howitworks.auth_status = false;
                    Main_Profile.sid = sid;
                    menuItem_auth.Text = "Подключиться";
                    AddToLog("Вы успешно продлили сессию", true);
                }
            }
            catch (Exception e)
            {
                statusBar_status.Text = MySuperExceptionHandler.Handle(e);
            }
        }

        public void Messages_userapi(string act)
        {
            if (howitworks.auth_status == false)
                AddToLog("Вы не авторизованы.", true);
            else
                try
                {
                    //Обнуляем массивы
                    if (act == "inbox")
                    {
                        Messages_API.in_m.id_message = new string[max_messages_in];
                        Messages_API.in_m.message = new string[max_messages_in];
                        Messages_API.in_m.unixtime = new string[max_messages_in];
                        Messages_API.in_m.sender_id = new string[max_messages_in];
                        Messages_API.in_m.read = new string[max_messages_in];
                        Messages_API.in_m.user_avatar = new string[max_messages_in];
                        Messages_API.in_m.user_avatar_small = new string[max_messages_in];
                        Messages_API.in_m.user_id = new string[max_messages_in];
                        Messages_API.in_m.user_name = new string[max_messages_in];
                        Messages_API.in_m.user_sex = new string[max_messages_in];
                        Messages_API.in_m.user_status = new string[max_messages_in];
                    }
                    else if (act == "outbox")
                    {
                        Messages_API.out_m.id_message = new string[max_messages_out];
                        Messages_API.out_m.message = new string[max_messages_out];
                        Messages_API.out_m.unixtime = new string[max_messages_out];
                        Messages_API.out_m.sender_id = new string[max_messages_out];
                        Messages_API.out_m.read = new string[max_messages_out];
                        Messages_API.out_m.user_avatar = new string[max_messages_out];
                        Messages_API.out_m.user_avatar_small = new string[max_messages_out];
                        Messages_API.out_m.user_id = new string[max_messages_out];
                        Messages_API.out_m.user_name = new string[max_messages_out];
                        Messages_API.out_m.user_sex = new string[max_messages_out];
                        Messages_API.out_m.user_status = new string[max_messages_out];
                    }
                    else
                    { 
                    
                    }

                    int num = 20;
                    if (act == "inbox")
                    {
                        num = max_messages_in;
                    }
                    else if (act == "outbox")
                    {
                        num = max_messages_out;
                    }
                    else
                    {
                        act = "message";
                    }

                    AddToLog("Составление запроса", true);
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://userapi.com/data?act=" + act + "&from=0&to=" + num + "&sid=" + Main_Profile.sid);
                    myHttpWebRequest.Method = "GET";
                    myHttpWebRequest.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                    myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                    myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                    myHttpWebRequest.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                    myHttpWebRequest.KeepAlive = true;
                    myHttpWebRequest.Headers.Add("Cache-Control", "no-cache");
                    myHttpWebRequest.AllowAutoRedirect = false;

                    AddToLog("Выполнение запроса", true);
                    // делаем запрос
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                    //Трафик
                    TrafficReceived += myHttpWebResponse.ContentLength;
                    label_stats_trafic.Invoke(new EventHandler(delegate { label_stats_trafic.Text = Methods.CountTraffic(TrafficReceived); })); 


                    string sLocation = myHttpWebResponse.Headers["Location"];//узнаем страницу на которую редирект

                    Stream messagepage = myHttpWebResponse.GetResponseStream();

                    StreamReader messagepage_reader = new StreamReader(messagepage, Encoding.UTF8);

                    string str = messagepage_reader.ReadToEnd();//Получаем всю страницу

                    //Закрываем потоки
                    myHttpWebResponse.Close();

                    //Обрабатываем json массив

                    int found_start = str.IndexOf("[");
                    int found_end = str.LastIndexOf("]");

                    str = str.Substring(found_start, found_end - found_start + 1);//1 потому что 1 символ последний не попадает

                    string[,] messages = new string[11, num];
                    int numbermessages = 0;
                    string part;

                    Regex r_part;
                    Match m_part;

                    found_start = str.IndexOf("{");
                    found_end = str.IndexOf("}");

                    while (found_start != -1 && found_end != -1)
                    {
                        part = str.Substring(found_start, found_end - found_start + 1);
                        if (act == "inbox")
                        {
                            r_part = new Regex("0:\"(?<message_id>\\d+)\",1:\"(?<unixtime>\\d+)\",2:[[]\"(?<message>.+)\"[]],5:\"(?<read>\\d+)\",4:[[]\"(?<sender_id>\\d+)\"],3:[[](?<receiver_id>\\d+),\"(?<receiver_name>.+)\",\"(?<receiver_avatar>.+)\",\"(?<receiver_avatar_small>.+)\",(?<receiver_sex>\\d+),(?<receiver_status>\\d+)[]]");
                        }
                        else
                        {
                            r_part = new Regex("0:\"(?<message_id>\\d+)\",1:\"(?<unixtime>\\d+)\",2:[[]\"(?<message>.+)\"[]],5:\"(?<read>\\d+)\",4:[[](?<receiver_id>\\d+),\"(?<receiver_name>.+)\",\"(?<receiver_avatar>.+)\",\"(?<receiver_avatar_small>.+)\",(?<receiver_sex>\\d+),(?<receiver_status>\\d+)[]],3:[[]\"(?<sender_id>\\d+)\"]");
                        }
                        m_part = r_part.Match(part);

                        messages[0, numbermessages] = m_part.Groups["message_id"].Value;
                        messages[1, numbermessages] = m_part.Groups["unixtime"].Value;
                        messages[2, numbermessages] = m_part.Groups["message"].Value;
                        messages[3, numbermessages] = m_part.Groups["read"].Value;
                        messages[4, numbermessages] = m_part.Groups["sender_id"].Value;
                        messages[5, numbermessages] = m_part.Groups["receiver_id"].Value;
                        messages[6, numbermessages] = m_part.Groups["receiver_name"].Value.Replace("\\t", " ");
                        messages[7, numbermessages] = m_part.Groups["receiver_avatar"].Value;
                        messages[8, numbermessages] = m_part.Groups["receiver_avatar_small"].Value;
                        messages[9, numbermessages] = m_part.Groups["receiver_sex"].Value;
                        messages[10, numbermessages] = m_part.Groups["receiver_status"].Value;

                        /*Добавляем в массив*/



                        if (act == "inbox")
                        {
                            Messages_API.in_m.id_message[numbermessages] = messages[0, numbermessages];
                            Messages_API.in_m.unixtime[numbermessages] = messages[1, numbermessages];
                            Messages_API.in_m.message[numbermessages] = messages[2, numbermessages];
                            Messages_API.in_m.read[numbermessages] = messages[3, numbermessages];
                            Messages_API.in_m.sender_id[numbermessages] = messages[4, numbermessages];
                            Messages_API.in_m.user_id[numbermessages] = messages[5, numbermessages];
                            Messages_API.in_m.user_name[numbermessages] = messages[6, numbermessages];
                            Messages_API.in_m.user_avatar[numbermessages] = messages[7, numbermessages];
                            Messages_API.in_m.user_avatar_small[numbermessages] = messages[8, numbermessages];
                            Messages_API.in_m.user_sex[numbermessages] = messages[9, numbermessages];
                            Messages_API.in_m.user_status[numbermessages] = messages[10, numbermessages];
                        }
                        else if (act == "outbox")
                        {
                            Messages_API.out_m.id_message[numbermessages] = messages[0, numbermessages];
                            Messages_API.out_m.unixtime[numbermessages] = messages[1, numbermessages];
                            Messages_API.out_m.message[numbermessages] = messages[2, numbermessages];
                            Messages_API.out_m.read[numbermessages] = messages[3, numbermessages];
                            Messages_API.out_m.sender_id[numbermessages] = messages[4, numbermessages];
                            Messages_API.out_m.user_id[numbermessages] = messages[5, numbermessages];
                            Messages_API.out_m.user_name[numbermessages] = messages[6, numbermessages];
                            Messages_API.out_m.user_avatar[numbermessages] = messages[7, numbermessages];
                            Messages_API.out_m.user_avatar_small[numbermessages] = messages[8, numbermessages];
                            Messages_API.out_m.user_sex[numbermessages] = messages[9, numbermessages];
                            Messages_API.out_m.user_status[numbermessages] = messages[10, numbermessages];
                        }
                        else
                        {

                        }


                        found_start = str.IndexOf("{", found_end);

                        if (found_start != -1)
                        { part += ","; }

                        str = str.Replace(part, "");

                        found_start = str.IndexOf("{");
                        found_end = (found_start != -1) ? str.IndexOf("}", found_start) : -1;

                        numbermessages++;
                    }

                    //Добавляем в listbox


                    if (numbermessages > 0)
                    {
                        if (act == "inbox")
                        {
                            comboBox_in_messages.Invoke(new EventHandler(delegate { comboBox_in_messages.Items.Clear(); }));
                            for (int i = 0; i < numbermessages; i++)
                            {
                                comboBox_in_messages.Invoke(new EventHandler(delegate { comboBox_in_messages.Items.Add(messages[2, i]); }));
                            }
                        }
                        else if (act == "outbox")
                        {
                            comboBox_out_messages.Invoke(new EventHandler(delegate { comboBox_out_messages.Items.Clear(); }));
                            for (int i = 0; i < numbermessages; i++)
                            {
                                comboBox_out_messages.Invoke(new EventHandler(delegate { comboBox_out_messages.Items.Add(messages[2, i]); }));
                            }
                        }
                        else
                        {

                        }
                       AddToLog("Список сообщений успешно загружен", true);
                    }
                    else
                    {
                        if (act == "inbox")
                        {
                            AddToLog("Список входящих сообщений пуст", true);
                        }
                        else if (act == "outbox")
                        {
                            AddToLog("Список исходящих сообщений пуст", true);
                        }
                        else
                        {
                            AddToLog("Список сообщений для данного друга пуст", true);
                        }
                    }

                }
                catch (Exception e)
                {
                    statusBar_status.Text = MySuperExceptionHandler.Handle(e);
                }
        }

        public void Messages_delete_userapi(string act)
        {
            if (howitworks.auth_status == false)
                AddToLog("Вы не авторизованы.", true);
            else
                try
                {
                    int arrayindex = -1;
                    string user_id = "";
                    string message_id = "";
                    if (Main_Menuitems.tag == 3)
                    {
                        comboBox_in_messages.Invoke(new EventHandler(delegate { arrayindex = comboBox_in_messages.SelectedIndex; }));
                        user_id = Messages_API.in_m.user_id[arrayindex];
                        message_id = Messages_API.in_m.id_message[arrayindex];
                    }
                    else if(Main_Menuitems.tag == 4)
                    {
                        comboBox_out_messages.Invoke(new EventHandler(delegate { arrayindex = comboBox_out_messages.SelectedIndex; }));
                        user_id = Messages_API.out_m.user_id[arrayindex];
                        message_id = Messages_API.out_m.id_message[arrayindex];
                    }
                    else
                    {
                     
                    }

                    AddToLog("Составление запроса", true);
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://userapi.com/data?act=" + act + "&id=" + Main_Profile.ID + "&wid=" + user_id + "_" + message_id + "&ts=64000095&sid=" + Main_Profile.sid);
                    myHttpWebRequest.Method = "GET";
                    myHttpWebRequest.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                    myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                    myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                    myHttpWebRequest.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                    myHttpWebRequest.KeepAlive = true;
                    myHttpWebRequest.AllowAutoRedirect = false;

                    AddToLog("Выполнение запроса", true);
                    // делаем запрос
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                    //Трафик
                    TrafficReceived += myHttpWebResponse.ContentLength;
                    label_stats_trafic.Invoke(new EventHandler(delegate { label_stats_trafic.Text = Methods.CountTraffic(TrafficReceived); })); 

                    string sLocation = myHttpWebResponse.Headers["Location"];//узнаем страницу на которую редирект

                    Stream messagepage = myHttpWebResponse.GetResponseStream();
                    StreamReader messagepage_reader = new StreamReader(messagepage, Encoding.UTF8);

                    string str = messagepage_reader.ReadToEnd();//Получаем всю страницу

                    //Закрываем потоки
                    myHttpWebResponse.Close();

                    Regex r_sid = new Regex("\"ok\":(?<ok>\\d+)");
                    Match m_sid = r_sid.Match(str);

                    string ok = (m_sid.Success) ? m_sid.Groups["ok"].Value.Trim() : "";

                    if (ok == "1")
                    {
                        AddToLog("Сообщение успешно удалено", true);

                        if (Main_Menuitems.tag == 3)
                        {
                            comboBox_in_messages.Invoke(new EventHandler(delegate { comboBox_in_messages.Items.RemoveAt(comboBox_in_messages.SelectedIndex); }));
                            label_message_area_in.Invoke(new EventHandler(delegate { label_message_area_in.Text = ""; }));
                            
                        }
                        else if (Main_Menuitems.tag == 4)
                        {
                            comboBox_out_messages.Invoke(new EventHandler(delegate { comboBox_out_messages.Items.RemoveAt(comboBox_out_messages.SelectedIndex); }));
                            label_message_area_out.Invoke(new EventHandler(delegate { label_message_area_out.Text = ""; }));
                            
                        }
                        else
                        {

                        }
                        
                    }
                    else
                    {
                        AddToLog("Сообщение не удалено", true);
                    }
                }
                catch (Exception e)
                {
                    statusBar_status.Text = MySuperExceptionHandler.Handle(e);
                }
        }


        /*Connection*/
    
        /// <summary>
        /// Прокси сервер
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        public void Proxy(string host, int port)
        {
            WebProxy proxy = new WebProxy(host, port);
            proxy.BypassProxyOnLocal = true;
            GlobalProxySelection.Select = proxy;
        }

        
        /******Настройки******/

        public void Settings_view_common()
        {
            if (howitworks.auth_status == false)
                AddToLog("Вы не авторизованы.", true);
            else
                try
                {
                    string hash;//
                    string name;
                    string surname;
                    string nickname;

                    /*Переменные начала и конца строки для парсинга*/
                    int found_start;
                    int found_end;

                    AddToLog("Составлени запроса", true);
                    //Запрос на страницу ввода запроса
                    HttpWebRequest myHttpWebRequest_status = (HttpWebRequest)HttpWebRequest.Create("http://vkontakte.ru/settings.php");
                    myHttpWebRequest_status.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                    myHttpWebRequest_status.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                    myHttpWebRequest_status.Headers.Add("Accept-Language", "ru");
                    myHttpWebRequest_status.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                    myHttpWebRequest_status.Headers["Accept-Encoding"] = "gzip";
                    myHttpWebRequest_status.Headers["Cookie"] = Main_Profile.sCookies;
                    myHttpWebRequest_status.AllowAutoRedirect = false;

                    // выполняем запрос
                    AddToLog("Выполнение запроса", true);
                    HttpWebResponse myHttpWebResponse_status = (HttpWebResponse)myHttpWebRequest_status.GetResponse();

                    Stream statuspage = myHttpWebResponse_status.GetResponseStream();

                    StreamReader statuspage_reader = new StreamReader(statuspage, Encoding.GetEncoding(1251));
                    string str = statuspage_reader.ReadToEnd();//Получаем всю страницу

                    //Закрываем потоки
                    myHttpWebResponse_status.Close();
                    statuspage.Close();
                    statuspage_reader.Close();

                    str = GzipCompress.DeCompressGzip(str);


                    //Чистим страницу
                    str = str.Replace("\n", "");
                    str = str.Replace("\r", "");
                    str = str.Replace("\t", "");
                    str = str.Trim();

                    //Получаем Hash-код
                    found_start = str.IndexOf("id=\"hash\" name=\"hash\" value=\"");
                    found_end = str.IndexOf("<input type=\"hidden\" id=\"nickname\" name=\"nickname\"");
                    hash = str.Substring(found_start, found_end - found_start);
                    hash = hash.Replace("id=\"hash\" name=\"hash\" value=\"", "");
                    hash = hash.Replace("\" />", "").Trim();

                    //Получаем Имя
                    found_start = str.IndexOf("id=\"first_name\" name=\"first_name\" value=\"");
                    found_end = str.IndexOf("<tr class=\"password confirm_password tallrow\">");
                    name = str.Substring(found_start, found_end - found_start);
                    name = name.Replace("\" /></td>", "").Replace("</tr>", "");
                    name = name.Replace("id=\"first_name\" name=\"first_name\" value=\"", "").Trim();

                    //Получаем Фамилию
                    found_start = str.IndexOf("id=\"last_name\" name=\"last_name\" value=\"");
                    found_end = str.IndexOf("<br /><small style=\"color:#777\">");
                    surname = str.Substring(found_start, found_end - found_start);
                    surname = surname.Replace("\" />", "");
                    surname = surname.Replace("id=\"last_name\" name=\"last_name\" value=\"", "").Trim();

                    //Получаем Никнейм
                    found_start = str.IndexOf("id=\"nickname\" name=\"nickname\" value=\"");
                    found_end = str.IndexOf("<tr class=\"password old_password tallrow\">");
                    nickname = str.Substring(found_start, found_end - found_start);
                    nickname = nickname.Replace("<input type=\"hidden\" id=\"subm\" name=\"subm\" value=\"1\" />", "");
                    nickname = nickname.Replace("\" />", "");
                    nickname = nickname.Replace("id=\"nickname\" name=\"nickname\" value=\"", "").Trim();


                    //Присваиваем значения
                    Main_settings.hash = hash;
                    Main_settings.nickname = nickname;

                    txt_name_settings.Invoke(new EventHandler(delegate { txt_name_settings.Text = name; }));
                    txt_surname_settings.Invoke(new EventHandler(delegate { txt_surname_settings.Text = surname; }));
                    txt_nickname_settings.Invoke(new EventHandler(delegate { txt_nickname_settings.Text = nickname; }));

                    btn_name_settings.Invoke(new EventHandler(delegate { btn_name_settings.Enabled = true; }));
                }
                catch (Exception e)
                {
                    statusBar_status.Text = MySuperExceptionHandler.Handle(e).ToString();
                }
        }

        public void Settings_change_name()
        {
            if (howitworks.auth_status == false)
                AddToLog("Вы не авторизованы.", true);
            else
                try
                {
                    //Присваимваем значения
                    string name = "";
                    string surname = "";
                    string nickname = Main_settings.nickname;
                    string hash = Main_settings.hash;

                    //Обнуляем массивы
                    txt_name_settings.Invoke(new EventHandler(delegate { name = txt_name_settings.Text; }));
                    txt_surname_settings.Invoke(new EventHandler(delegate { surname = txt_surname_settings.Text; }));

                    AddToLog("Составление запроса", true);
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://vkontakte.ru/settings.php");
                    myHttpWebRequest.Method = "POST";
                    myHttpWebRequest.Referer = "http://vkontakte.ru/settings.php";
                    myHttpWebRequest.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                    myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                    myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                    myHttpWebRequest.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                    myHttpWebRequest.Headers["Accept-Encoding"] = "gzip";
                    myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    myHttpWebRequest.Headers["Cookie"] = Main_Profile.sCookies;
                    myHttpWebRequest.AllowAutoRedirect = false;

                    name = (String.IsNullOrEmpty(name)) ? "" : HttpUtility.UrlEncode(name, site_encoding);
                    surname = (String.IsNullOrEmpty(surname)) ? "" : HttpUtility.UrlEncode(surname, site_encoding);
                    nickname = (String.IsNullOrEmpty(nickname)) ? "" : HttpUtility.UrlEncode(nickname, site_encoding);


                    //Строка запроса
                    string sQueryString = "act=change_name&hash=" + hash + "&nickname=" + nickname + "&subm=1&first_name=" + name + "&last_name=" + surname + "";

                    byte[] ByteArr = System.Text.Encoding.GetEncoding(65001).GetBytes(sQueryString);
                    myHttpWebRequest.ContentLength = ByteArr.Length;

                    Stream sss = myHttpWebRequest.GetRequestStream();
                    sss.Write(ByteArr, 0, ByteArr.Length);

                    sss.Close();

                    AddToLog("Выполняем запрос...", true);

                    // делаем запрос
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                    if (!String.IsNullOrEmpty(myHttpWebResponse.Headers["Set-Cookie"]))
                    {
                        Main_Profile.sCookies = myHttpWebResponse.Headers["Set-Cookie"];
                    }

                    string sLocation = myHttpWebResponse.Headers["Location"];//узнаем страницу на которую редирект

                    //Закрываем потоки
                    myHttpWebResponse.Close();

                    if (sLocation == "settings.php?m=5")
                    {
                        AddToLog("Данные успешно изменены.", true);
                    }
                    else
                    {
                        AddToLog("Данные не изменены.", true);
                    }

                    btn_name_settings.Invoke(new EventHandler(delegate { btn_name_settings.Enabled = false; }));
                }

                catch (Exception e)
                {
                    statusBar_status.Text = MySuperExceptionHandler.Handle(e).ToString();
                }
        }


        /******Timer******/
        public void Timer_notification()
        {
            if (howitworks.auth_status == true)
                try
                {
                    //Запрос на страницу ввода запроса
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://pda.vkontakte.ru/");
                    myHttpWebRequest.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                    myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                    myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                    myHttpWebRequest.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                    myHttpWebRequest.Headers["Accept-Encoding"] = "none";
                    //Устанавливаем отпарсинные cookies
                    myHttpWebRequest.Headers["Cookie"] = Main_Profile.sCookies;
                    myHttpWebRequest.AllowAutoRedirect = false;
                    // выполняем запрос

                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                    Stream page = myHttpWebResponse.GetResponseStream();

                    StreamReader page_reader = new StreamReader(page, Encoding.GetEncoding(65001));
                    string str = page_reader.ReadToEnd();//Получаем всю страницу

                    //Закрываем потоки
                    myHttpWebResponse.Close();
                    page.Close();
                    page_reader.Close();

                    //Почистили страницу
                    str = str.Replace("\n", "");
                    str = str.Replace("\r", "");
                    str = str.Replace("\t", "");
                    str = str.Trim();


                    Regex messages = new Regex("Мои(\\s)Сообщения(\\s)[(]<b>(?<num_messages>\\d+)</b>[)]");
                    Match v_messages = messages.Match(str);

                    if (v_messages.Success)//Если есть вхождение
                    {
                        /*
                        StringBuilder HTMLString = new StringBuilder();
                        HTMLString.Append("<html><body>");
                        HTMLString.Append("<b>Новых сообщений: <font color=\"red\">" + v_messages.Groups["num_messages"].Value + "</font></b>");
                        HTMLString.Append("<form method=\'GET\' action=notify>");
                        HTMLString.Append("<input type=button name='cmd:2' value='Закрыть'>");
                        HTMLString.Append("</body></html>");
                        
                        notification.Critical = true;
                        notification.BalloonChanged += new BalloonChangedEventHandler(notification_BalloonChanged);
                        notification.ResponseSubmitted += new ResponseSubmittedEventHandler(notification_ResponseSubmitted);
                        notification.InitialDuration = 15;
                        notification.Icon = Properties.Resources.icon;
                        notification.Text = HTMLString.ToString();
                        notification.Visible = true;
                        */

                        string filename = "notification.wav";
                        string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\" + filename;
                        Sound sound = new Sound(path);
                        sound.Play();

                        Clear_New_Messages();
                    }
                }
                catch (Exception e)
                {
                    statusBar_status.Text = MySuperExceptionHandler.Handle(e).ToString();
                }
        }

        /*Очищаем новые сообщения*/
        public void Clear_New_Messages()
        {
            if (howitworks.auth_status == true)
                try
                {
                    int found_start;
                    int found_end;

                    //Запрос на страницу ввода запроса
                    HttpWebRequest myHttpWebRequest_messages = (HttpWebRequest)HttpWebRequest.Create("http://vkontakte.ru/mail.php");
                    myHttpWebRequest_messages.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                    myHttpWebRequest_messages.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                    myHttpWebRequest_messages.Headers.Add("Accept-Language", "ru");
                    myHttpWebRequest_messages.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                    //Запаковали
                    myHttpWebRequest_messages.Headers["Accept-Encoding"] = "gzip";
                    //Устанавливаем отпарсинные cookies
                    myHttpWebRequest_messages.Headers["Cookie"] = Main_Profile.sCookies;
                    myHttpWebRequest_messages.AllowAutoRedirect = false;
                    // выполняем запрос
                    HttpWebResponse myHttpWebResponse_messages = (HttpWebResponse)myHttpWebRequest_messages.GetResponse();
                    Stream messagepage = myHttpWebResponse_messages.GetResponseStream();

                    StreamReader messagepage_reader = new StreamReader(messagepage, Encoding.GetEncoding(1251));

                    string str = messagepage_reader.ReadToEnd();//Получаем всю страницу

                    //Закрываем потоки
                    myHttpWebResponse_messages.Close();
                    messagepage.Close();
                    messagepage_reader.Close();


                    str = GzipCompress.DeCompressGzip(str);


                    //Чистим страницу
                    str = str.Replace("\n", "");
                    str = str.Replace("\r", "");
                    str = str.Replace("\t", "");
                    str = str.Trim();

                    /*Массив*/

                    string[] messages_id = new string[0];
                    string body;
                    int num_messages = 0;


                    found_start = str.IndexOf("<tr  id=");
                    found_end = str.IndexOf("</table>");
                    str = str.Substring(found_start, found_end - found_start);

                    found_start = str.IndexOf("<tr  id");
                    found_end = str.IndexOf("</tr>");

                    while (found_start != -1 && found_end != -1)
                    {
                        /*Берем одну запись*/
                        body = str.Substring(found_start, found_end);
                        body += "</tr>";


                        /*ID сообщения и отправителя*/
                        Regex id_message = new Regex("id=\"mess(?<id>\\d+)\">");//ID message
                        Match v_id_messages = id_message.Match(body);

                        /*Повышаем размер массива # +1 потому что размер массива а не элемент*/
                        messages_id = (string[])Methods.IncreaseArray(messages_id, num_messages + 1);

                        //Добавляем в массив id сообщения
                        messages_id[num_messages] = (v_id_messages.Success) ? v_id_messages.Groups["id"].Value : "";

                        /*И потом удаляем запись*/
                        str = str.Replace(body, "");

                        found_start = str.IndexOf("<tr  id=\"");
                        found_end = str.IndexOf("</tr>");
                        num_messages++;
                    }


                    //Составляем строку запроса
                    string srcstring = "";

                    for (int i = 0; i < num_messages; i++)
                    {
                        srcstring += "post" + i + "=" + messages_id[i] + "&";
                    }

                    //Удаляем последний символ из строки
                    srcstring = srcstring.Remove(srcstring.Length - 1, 1);

                    //Теперь можно составлять запрос на прочитанные сообщения

                    HttpWebRequest myHttpWebRequest_ = (HttpWebRequest)HttpWebRequest.Create("http://vkontakte.ru/mail.php");
                    myHttpWebRequest_.Method = "POST";
                    myHttpWebRequest_.Referer = "http://vkontakte.ru/mail.php";
                    myHttpWebRequest_.UserAgent = "Mozila/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                    myHttpWebRequest_.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
                    myHttpWebRequest_.Headers.Add("Accept-Language", "ru");
                    myHttpWebRequest_.Headers.Add("Accept-Charset", "iso-8859-1, utf-8, utf-16");
                    myHttpWebRequest_.Headers["Accept-Encoding"] = "gzip";
                    myHttpWebRequest_.Headers["Cookie"] = Main_Profile.sCookies;
                    myHttpWebRequest_.ContentType = "application/x-www-form-urlencoded";
                    myHttpWebRequest_.AllowAutoRedirect = false;

                    //Составляем строку запроса
                    string sQueryString_ = "act=msgRead&inOut=0&st=0&" + srcstring;

                    byte[] ByteArr_ = System.Text.Encoding.GetEncoding(1251).GetBytes(sQueryString_);
                    myHttpWebRequest_.ContentLength = ByteArr_.Length;

                    Stream sss_ = myHttpWebRequest_.GetRequestStream();
                    sss_.Write(ByteArr_, 0, ByteArr_.Length);

                    sss_.Close();

                    // делаем запрос
                    HttpWebResponse myHttpWebResponse_ = (HttpWebResponse)myHttpWebRequest_.GetResponse();

                    //Закрываем потоки
                    myHttpWebResponse_.Close();
                }

                catch (Exception e)
                {
                    statusBar_status.Text = MySuperExceptionHandler.Handle(e).ToString();
                }
        }



        /*Events*/
       
        /*task bar button*/
        private void notifyIcon_Click(object sender, EventArgs e)
        {
            ShowButton_Click();
        }

        /*Timer*/
        private void Timer_notify_Tick(object sender, EventArgs e)
        {
            Threads.notification = new Thread(new ThreadStart(Timer_notification));
            Threads.notification.Name = "notification";
            Threads.notification.Start();
        }


        /*Notification*/
        void notification_ResponseSubmitted(object sender, ResponseSubmittedEventArgs e)
        {
            notification.Visible = false;
        }

        void notification_BalloonChanged(object sender, BalloonChangedEventArgs e)
        {
            //if (e.Visible)
            //{
                //notification.Visible = false;
            //}
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            Stats();
        }

        /*Форма*/
        private void Main_Form_Load(object sender, EventArgs e)
        {
            //Таймер
            timer = new System.Windows.Forms.Timer();
            timer.Tick += new EventHandler(Timer_Tick);
            timer.Interval = 1000;
            timer.Enabled = true;

            if (File.Exists(path_to_settings))
            {
                Main_Settings_API.theme = new string[0];
                Main_Settings_API.parameter = new string[0];
                Main_Settings_API.value = new string[0];

                Regex r_param;
                Match m_param;

                string input;
                int count = 0;

                using (StreamReader sr = new StreamReader(path_to_settings,Encoding.GetEncoding(1251)))
                {
                    while ((input = sr.ReadLine()) != null)
                    {
                        Main_Settings_API.theme = (string[])Methods.IncreaseArray(Main_Settings_API.theme, count + 1);
                        Main_Settings_API.parameter = (string[])Methods.IncreaseArray(Main_Settings_API.parameter, count + 1);
                        Main_Settings_API.value = (string[])Methods.IncreaseArray(Main_Settings_API.value, count + 1);

                        r_param = new Regex("[[](?<parameter>.+)[]]");
                        m_param = r_param.Match(input);

                        if (m_param.Success)
                        {
                            Main_Settings_API.theme[count] = (m_param.Success) ? m_param.Groups["parameter"].Value : "";
                        }
                        else
                        {
                            Main_Settings_API.theme[count] = "";
                            Main_Settings_API.parameter[count] = input.Substring(0, input.IndexOf("=", 0));
                            Main_Settings_API.value[count] = input.Substring(input.IndexOf("=", 0) + 1);
                        }
                        count++;
                    }
                }

                int profile_name = Array.IndexOf(Main_Form.Main_Settings_API.parameter, "profile_name");
                int email = Array.IndexOf(Main_Form.Main_Settings_API.parameter, "email");
                int password = Array.IndexOf(Main_Form.Main_Settings_API.parameter, "password");
                int save_cookie = Array.IndexOf(Main_Form.Main_Settings_API.parameter, "save_cookie");
                int save_password = Array.IndexOf(Main_Form.Main_Settings_API.parameter, "save_password");
                int connect_on_launch = Array.IndexOf(Main_Form.Main_Settings_API.parameter, "connect_on_launch");

                Main_Profile.name_profile = (profile_name != -1) ? Main_Form.Main_Settings_API.value[profile_name] : "";
                Main_Profile.sEmail = (email != -1) ? Main_Form.Main_Settings_API.value[email] : "";
                Main_Profile.sPassword = (password != -1) ? Main_Form.Main_Settings_API.value[password] : "";
                Main_Profile.save_cookie = (save_cookie != -1) ? ((Main_Form.Main_Settings_API.value[save_cookie] == "0") ? true : false) : false;
                Main_Profile.save_password = (save_password != -1) ? ((Main_Form.Main_Settings_API.value[save_password] == "0") ? false : true) : false;
                Main_Profile.connect_on_launch = (connect_on_launch != -1) ? ((Main_Form.Main_Settings_API.value[connect_on_launch] == "0") ? false : true) : false;
            }
        }

        private void Main_Form_Closing(object sender, CancelEventArgs e)
        {
            notifyIcon.Remove();
            timer.Enabled = false;
            timer.Tick -= new EventHandler(Timer_Tick);
            timer.Dispose();
        }

        #region Левое меню



        #endregion
        
        #region Правое меню
     
        #endregion

        /******Обычные события******/

        /*Статусы*/
        private void btn_set_status_Click(object sender, EventArgs e)
        {
            ThreadFriends_set_status_api status = new ThreadFriends_set_status_api(txt_set_status.Text, this);
            Threads.status_thread = new Thread(new ThreadStart(status.go));
            Threads.status_thread.Name = "set_status";
            Threads.status_thread.Start();
            SipShowIM(SIPF_OFF);
        }

        private void btn_current_status_Click(object sender, EventArgs e)
        {

        }

        
        /*Отправленные сообщения*/

        private void btn_new_message_out_Click(object sender, EventArgs e)
        {
          
        }

        private void btn_reply_message_out_Click(object sender, EventArgs e)
        {
            if (comboBox_out_messages.SelectedIndex >= 0 && comboBox_out_messages.Items[comboBox_out_messages.SelectedIndex].ToString() != "")
            {
                panel1_send_message_tofriend.BringToFront();
                if (Main_Menuitems.tag != 1)
                {
                    switch (Main_Menuitems.tag)
                    {
                        case 1:
                            Main_Menuitems.friends_send_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.friends_send_message, 0);
                            break;
                        case 2:
                            Main_Menuitems.friends = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.friends, 0);
                            break;
                        case 3:
                            Main_Menuitems.messages_in = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_in, 0);
                            break;
                        case 4:
                            Main_Menuitems.messages_out = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_out, 0);
                            break;
                        case 5:
                            Main_Menuitems.status = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.status, 0);
                            break;
                        case 6:
                            Main_Menuitems.settings_common = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.settings_common, 0);
                            break;
                        case 7:
                            Main_Menuitems.messages_reply_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_reply_message, 0);
                            break;
                        case 8:
                            Main_Menuitems.messages_new_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_new_message, 0);
                            break;
                    }

                    menuItem.MenuItems.Clear();
                    menuItem.MenuItems.Add(this.MenuItem_messages_send_message);
                    menuItem.MenuItems.Add(this.MenuItem_messages_cancel_send_message);
                    Main_Menuitems.tag = 1;
                    Messages_API.messages_list_index = 4;
                    Main_Friends_API.friend_list_index = comboBox_out_messages.SelectedIndex;
                    label_friend_info.Text = comboBox_out_messages.Items[comboBox_out_messages.SelectedIndex].ToString();
                    SipShowIM(SIPF_ON); //Отображаем клавиатуру
                }
            }
            else
            {
                AddToLog("Не выбрано сообщение", true);
            }
        }

        private void btn_delete_message_out_Click(object sender, EventArgs e)
        {
            if (comboBox_out_messages.SelectedIndex != -1)
            {
                Thread_delete_message api = new Thread_delete_message("del_outbox", this);
                Threads.messages_thread = new Thread(new ThreadStart(api.go));
                Threads.messages_thread.Name = "delete_message";
                Threads.messages_thread.Start();
            }
            else
            {
                AddToLog("Вы не выбрали сообщение", true);
            }
        }

        private void comboBox_out_messages_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        /*Принятые сообщения*/

        private void comboBox_in_messages_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void btn_new_message_in_Click(object sender, EventArgs e)
        {
          
        }

        private void btn_reply_message_in_Click(object sender, EventArgs e)
        {
            if (comboBox_in_messages.SelectedIndex >= 0 && comboBox_in_messages.Items[comboBox_in_messages.SelectedIndex].ToString() != "")
            {
                panel1_send_message_tofriend.BringToFront();
                if (Main_Menuitems.tag != 1)
                {
                    switch (Main_Menuitems.tag)
                    {
                        case 1:
                            Main_Menuitems.friends_send_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.friends_send_message, 0);
                            break;
                        case 2:
                            Main_Menuitems.friends = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.friends, 0);
                            break;
                        case 3:
                            Main_Menuitems.messages_in = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_in, 0);
                            break;
                        case 4:
                            Main_Menuitems.messages_out = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_out, 0);
                            break;
                        case 5:
                            Main_Menuitems.status = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.status, 0);
                            break;
                        case 6:
                            Main_Menuitems.settings_common = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.settings_common, 0);
                            break;
                        case 7:
                            Main_Menuitems.messages_reply_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_reply_message, 0);
                            break;
                        case 8:
                            Main_Menuitems.messages_new_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_new_message, 0);
                            break;
                    }

                    menuItem.MenuItems.Clear();
                    menuItem.MenuItems.Add(this.MenuItem_messages_send_message);
                    menuItem.MenuItems.Add(this.MenuItem_messages_cancel_send_message);
                    Main_Menuitems.tag = 1;
                    Messages_API.messages_list_index = 3;
                    Main_Friends_API.friend_list_index = comboBox_in_messages.SelectedIndex;
                    label_friend_info.Text = comboBox_in_messages.Items[comboBox_in_messages.SelectedIndex].ToString();
                }
            }
            else
            {
                AddToLog("Не выбрано сообщение", true);
            }
        }

        private void btn_delete_message_in_Click(object sender, EventArgs e)
        {
            if (comboBox_in_messages.SelectedIndex != -1)
            {
                Thread_delete_message api = new Thread_delete_message("del_inbox", this);
                Threads.messages_thread = new Thread(new ThreadStart(api.go));
                Threads.messages_thread.Name = "delete_message";
                Threads.messages_thread.Start();
            }
            else
            {
                AddToLog("Вы не выбрали сообщение", true);
            }
        }

      
        /*Contextmenu*/

        private void menuItem_getinfo_contact_Click(object sender, EventArgs e)
        {
            ThreadFriends_list_api api;
            if (MenuItem_friends_all_online.Checked)
            {
                api = new ThreadFriends_list_api("friends_online", this);
            }
            else
            {
                api = new ThreadFriends_list_api("friends", this);
            }

            Threads.status_thread = new Thread(new ThreadStart(api.go));
            Threads.status_thread.Name = "friends";
            Threads.status_thread.Start();
        }

        private void menuItem_download_all_Click(object sender, EventArgs e)
        {
            contextMenu_friends_all_online.Checked = (contextMenu_friends_all_online.Checked) ? false : true;
        }

        private void menuItem_download_online_Click(object sender, EventArgs e)
        {
            if (listBox_friends_list.SelectedIndex >= 0 && listBox_friends_list.Items[listBox_friends_list.SelectedIndex].ToString() != "")
            {
                panel1_send_message_tofriend.BringToFront();
                if (Main_Menuitems.tag != 1)
                {
                    switch (Main_Menuitems.tag)
                    {
                        case 1:
                            Main_Menuitems.friends_send_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.friends_send_message, 0);
                            break;
                        case 2:
                            Main_Menuitems.friends = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.friends, 0);
                            break;
                        case 3:
                            Main_Menuitems.messages_in = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_in, 0);
                            break;
                        case 4:
                            Main_Menuitems.messages_out = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_out, 0);
                            break;
                        case 5:
                            Main_Menuitems.status = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.status, 0);
                            break;
                        case 6:
                            Main_Menuitems.settings_common = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.settings_common, 0);
                            break;
                        case 7:
                            Main_Menuitems.messages_reply_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_reply_message, 0);
                            break;
                        case 8:
                            Main_Menuitems.messages_new_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_new_message, 0);
                            break;
                    }

                    menuItem.MenuItems.Clear();
                    menuItem.MenuItems.Add(this.MenuItem_messages_send_message);
                    menuItem.MenuItems.Add(this.MenuItem_messages_cancel_send_message);
                    Main_Menuitems.tag = 1;
                    Main_Friends_API.friend_list_index = listBox_friends_list.SelectedIndex;
                    label_friend_info.Text = listBox_friends_list.Items[listBox_friends_list.SelectedIndex].ToString();
                }
            }
            else
            {
                AddToLog("Не выбран контакт для отправки сообщения", true);
            }
        }

        private void menuItem_delete_contact_Click(object sender, EventArgs e)
        {
            if (listBox_friends_list.SelectedIndex >= 0 && listBox_friends_list.Items[listBox_friends_list.SelectedIndex].ToString() != "")
            {
                listBox_friends_list.Items.Remove(listBox_friends_list.SelectedItem);
            }
            else
            {
                AddToLog("Не выбран контакт", true);
            }
        }

        private void menuItem_send_message_tofriend_contextmenu_Click(object sender, EventArgs e)
        {
            if (listBox_friends_list.SelectedIndex >= 0 && listBox_friends_list.Items[listBox_friends_list.SelectedIndex].ToString() != "")
            {
                Main_Friends.Send_message = true;
                label_friend_info.Text = listBox_friends_list.Items[listBox_friends_list.SelectedIndex].ToString();
                btn_send_message_tofriend.Enabled = true;

                string currentname = listBox_friends_list.Items[listBox_friends_list.SelectedIndex].ToString();
                //listBox_friends_list.Invoke(new EventHandler(delegate { currentname = listBox_friends_list.Items[listBox_friends_list.SelectedIndex].ToString(); }));
                //Получаем ID Записи
                //Создаем массив для заполнения закодированными уже элементами, Main_Friends.name не трогаем
                string[] decodedarray = new string[Main_Friends.name.Length];
                int countarray = 0;
                //Для каждого из элементов массива Main_Friends.name декодируем эелемент и добавляем в новый массив

                string[] fullname = new string[Main_Friends.id.Length];
                for (int i = 0; i < Main_Friends.id.Length; i++)
                {
                    fullname[i] = string.Concat(Main_Friends.name[i], " ", Main_Friends.surname[i]);//Общая строки имя+фамилия
                }

                foreach (string decodedname in fullname)
                {
                    decodedarray[countarray] = HttpUtility.HtmlDecode(decodedname);
                    countarray++;
                }

                int arrayindex = Array.IndexOf(decodedarray, currentname, 0, decodedarray.Length);

                Main_send_message_to_friend.ID = Main_Friends.id[arrayindex];// ID получателя

                panel1_send_message_tofriend.BringToFront();
            }
            else
            {
                Main_Friends.Send_message = false;
                AddToLog("Не выбран контакт", true);
                btn_send_message_tofriend.Enabled = false;
            }
        }


        
        /*Buttons*/

        #region Управление listbox_friends_list хард-клавишами

        private void listbox_friends_list_KeyDown(object sender, KeyEventArgs e)
        {
            listBox_friends_list.SelectNextControl(this, true, false, false, true);
        }

        private void listbox_friends_list_KeyUp(object sender, KeyEventArgs e)
        {
            listBox_friends_list.SelectNextControl(this, true, false, false, true);
        }

        private void listbox_friends_list_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (listBox_friends_list.SelectedIndex >= 0 && listBox_friends_list.Items[listBox_friends_list.SelectedIndex].ToString() != "")
            {
                panel1_send_message_tofriend.BringToFront();
                if (Main_Menuitems.tag != 1)
                {
                    switch (Main_Menuitems.tag)
                    {
                        case 1:
                            Main_Menuitems.friends_send_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.friends_send_message, 0);
                            break;
                        case 2:
                            Main_Menuitems.friends = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.friends, 0);
                            break;
                        case 3:
                            Main_Menuitems.messages_in = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_in, 0);
                            break;
                        case 4:
                            Main_Menuitems.messages_out = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_out, 0);
                            break;
                        case 5:
                            Main_Menuitems.status = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.status, 0);
                            break;
                        case 6:
                            Main_Menuitems.settings_common = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.settings_common, 0);
                            break;
                        case 7:
                            Main_Menuitems.messages_reply_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_reply_message, 0);
                            break;
                        case 8:
                            Main_Menuitems.messages_new_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_new_message, 0);
                            break;
                    }

                    menuItem.MenuItems.Clear();
                    menuItem.MenuItems.Add(this.MenuItem_messages_send_message);
                    menuItem.MenuItems.Add(this.MenuItem_messages_cancel_send_message);
                    Main_Menuitems.tag = 1;
                    Main_Friends_API.friend_list_index = listBox_friends_list.SelectedIndex;
                    label_friend_info.Text = listBox_friends_list.Items[listBox_friends_list.SelectedIndex].ToString();
                }
            }
            else
            {
                AddToLog("Не выбран контакт для отправки сообщения", true);
            }
        }

        #endregion



        private void btn_send_message_tofriend_Click(object sender, EventArgs e)
        {
            string act = "add_message";
            ThreadFriends_send_message_api api = null;
            if (Messages_API.messages_list_index == 3)
            {
                api = new ThreadFriends_send_message_api(Messages_API.in_m.user_id[Main_Friends_API.friend_list_index], txt_send_message_tofriend.Text, act, this);
            }
            else if (Messages_API.messages_list_index == 4)
            {
                api = new ThreadFriends_send_message_api(Messages_API.out_m.user_id[Main_Friends_API.friend_list_index], txt_send_message_tofriend.Text, act, this);
            }
            else
            {
                api = new ThreadFriends_send_message_api(Main_Friends_API.id[Main_Friends_API.friend_list_index], txt_send_message_tofriend.Text, act, this);
            }
            Threads.messages_thread = new Thread(new ThreadStart(api.go));
            Threads.messages_thread.Name = "send_message_tofriend";
            Threads.messages_thread.Start();
            
            if (Main_Menuitems.tag != 2)
            {
                switch (Main_Menuitems.tag)
                {
                    case 1:
                        Main_Menuitems.friends_send_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_send_message, 0);
                        break;
                    case 2:
                        Main_Menuitems.friends = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends, 0);
                        break;
                    case 3:
                        Main_Menuitems.messages_in = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_in, 0);
                        break;
                    case 4:
                        Main_Menuitems.messages_out = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_out, 0);
                        break;
                    case 5:
                        Main_Menuitems.status = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.status, 0);
                        break;
                    case 6:
                        Main_Menuitems.settings_common = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.settings_common, 0);
                        break;
                    case 7:
                        Main_Menuitems.messages_reply_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_reply_message, 0);
                        break;
                    case 8:
                        Main_Menuitems.messages_new_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_new_message, 0);
                        break;
                    case 9:
                        Main_Menuitems.friends_online = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_online, 0);
                        break;
                    case 10:
                        Main_Menuitems.friends_mutual = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_mutual, 0);
                        break;
                    case 11:
                        Main_Menuitems.friends_new = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_new, 0);
                        break;
                }

                menuItem.MenuItems.Clear();
                menuItem.MenuItems.Add(this.MenuItem_friends_refresh);
                menuItem.MenuItems.Add(this.MenuItem_friends_all_online);
                menuItem.MenuItems.Add(this.MenuItem_friends_send_message);
                menuItem.MenuItems.Add(this.MenuItem_friends_get_contacts);
                menuItem.MenuItems.Add(this.MenuItem_friends_delete_contact);

                Main_Menuitems.tag = 2;
            }
        }

        private void btn_send_message_reply_Click(object sender, EventArgs e)
        {
          
        }

        /*Settings*/

        private void btn_name_settings_Click(object sender, EventArgs e)
        {
            Threads.settings_change_name_thread = new Thread(new ThreadStart(Settings_change_name));
            Threads.settings_change_name_thread.Name = "common_settings_change_name";
            Threads.settings_change_name_thread.Start();
        }

        private void btn_nickname_settings_Click(object sender, EventArgs e)
        {

        }

        /*Стена*/

        private void menuItem_wall_Click(object sender, EventArgs e)
        {

        }

        private void comboBox_wall_messages_list_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void btn_wall_messages_tofriendmessage_Click(object sender, EventArgs e)
        {
            if (comboBox_wall_messages_list.SelectedIndex >= 0 && comboBox_wall_messages_list.Items[comboBox_wall_messages_list.SelectedIndex].ToString() != "")
            {
                Main_Friends.Send_message = true;
                label_friend_info.Text = comboBox_wall_messages_list.Items[comboBox_wall_messages_list.SelectedIndex].ToString();
                btn_send_message_tofriend.Enabled = true;

                string currentmessage = comboBox_wall_messages_list.Items[comboBox_wall_messages_list.SelectedIndex].ToString();

                string[] decodedarray = new string[Main_Wall.text.Length];
                
                int countarray = 0;
                foreach (string decodedname in Main_Wall.text)
                {
                    decodedarray[countarray] = HttpUtility.HtmlDecode(decodedname);
                    countarray++;
                }

                int arrayindex = Array.IndexOf(decodedarray, currentmessage, 0, decodedarray.Length);
                Main_send_message_to_friend.ID = Main_Wall.id[arrayindex];
                panel1_send_message_tofriend.BringToFront();
                SipShowIM(SIPF_ON);
            }
            else
            {
                Main_Friends.Send_message = false;
                AddToLog("Не выбран контакт", true);
                btn_send_message_tofriend.Enabled = false;
            }
        }

        private void btn_wall_messages_deletemessage_Click(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //byte[] soundfile = BeOnline.Properties.Resources.notification;
           // MemoryStream ms = new MemoryStream();
           // ms.Write(soundfile, 0, soundfile.Length);
           // Sound sound = new Sound(ms);
            
            
            string filename = "notification.wav";
            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\" + filename;
            Sound sound = new Sound(path);
            sound.Play();
        }

        #region пальцеориентированное меню
        private void rightarrowButton_Click(object sender, EventArgs e)
        {
            if (howitworks.show_picture == true)
            {
                this.rightarrowButton.Image = leftarrow;
                panel_menu.Visible = true;
                howitworks.show_picture = false;
            }
            else
            {
                this.rightarrowButton.Image = rightarrow;
                panel_menu.Visible = false;
                howitworks.show_picture = true;
            }
        }

        private void authButton_Click(object sender, EventArgs e)
        {
          
        }

        private void disconnectButton_Click(object sender, EventArgs e)
        {
          
        }

        private void wallButton_Click(object sender, EventArgs e)
        {
            panel10_wall_messages.BringToFront();
        }

        private void messagesButton_Click(object sender, EventArgs e)
        {
            panel3_in_messages.BringToFront();
        }

        private void friendsButton_Click(object sender, EventArgs e)
        {
            panel2_list_friends.BringToFront();
        }

        private void groupsButton_Click(object sender, EventArgs e)
        {

        }
        #endregion

        private void menuItem3_Click(object sender, EventArgs e)
        {
            ThreadFriends_list_api friends_list_api = new ThreadFriends_list_api("friends", this);
            Thread go = new Thread(new ThreadStart(friends_list_api.go));
            go.Name = "friends";
            go.Start();
        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
            Threads.status_thread = new Thread(new ThreadStart(Auth_userapi));
            Threads.status_thread.Name = "friends_userpapi";
            Threads.status_thread.Start();
        }

        private void menuItem5_Click(object sender, EventArgs e)
        {
            Threads.status_thread = new Thread(new ThreadStart(History_status_userapi));
            Threads.status_thread.Name = "history_status_userapi";
            Threads.status_thread.Start();
        }

        private void menuItem6_Click(object sender, EventArgs e)
        {
            Threads.status_thread = new Thread(new ThreadStart(Logout_userapi));
            Threads.status_thread.Name = "Logout_userapi";
            Threads.status_thread.Start();
        }

        private void menuItem7_Click(object sender, EventArgs e)
        {

        }

        private void menuItem10_Click(object sender, EventArgs e)
        {
            Threads.status_thread = new Thread(new ThreadStart(Clear_status_userapi));
            Threads.status_thread.Name = "Delete_status_userapi";
            Threads.status_thread.Start();
        }

        private void menuItem_minimize_Click(object sender, EventArgs e)
        {
            MinimizeButton_Click();
        }

        private void menuItem_about_Click(object sender, EventArgs e)
        {
            About about = new About();
            about.Show();
        }

        private void menuItem_exit_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }

        private void menuItem_profile_Click(object sender, EventArgs e)
        {
            Profile profile = new Profile();
            profile.Show();
            SipShowIM(SIPF_ON);
        }

        private void menuItem_status_Click(object sender, EventArgs e)
        {
            panel5_status.BringToFront();

            if (Main_Menuitems.tag != 5)
            {
                switch (Main_Menuitems.tag)
                {
                    case 1:
                        Main_Menuitems.friends_send_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_send_message, 0);
                        break;
                    case 2:
                        Main_Menuitems.friends = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends, 0);
                        break;
                    case 3:
                        Main_Menuitems.messages_in = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_in, 0);
                        break;
                    case 4:
                        Main_Menuitems.messages_out = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_out, 0);
                        break;
                    case 5:
                        Main_Menuitems.status = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.status, 0);
                        break;
                    case 6:
                        Main_Menuitems.settings_common = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.settings_common, 0);
                        break;
                    case 7:
                        Main_Menuitems.messages_reply_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_reply_message, 0);
                        break;
                    case 8:
                        Main_Menuitems.messages_new_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_new_message, 0);
                        break;
                }

                menuItem.MenuItems.Clear();
                menuItem.MenuItems.Add(this.MenuItem_status_refresh);
                menuItem.MenuItems.Add(this.MenuItem_status_set);
                menuItem.MenuItems.Add(this.MenuItem_status_delete);
                menuItem.MenuItems.Add(this.MenuItem_status_history);
                Main_Menuitems.tag = 5;
                SipShowIM(SIPF_ON);
            }


        }

        private void menuItem_friend_all_Click(object sender, EventArgs e)
        {
            panel2_list_friends.BringToFront();

            if (Main_Menuitems.tag != 2)
            {
                switch (Main_Menuitems.tag)
                {
                    case 1:
                        Main_Menuitems.friends_send_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_send_message, 0);
                        break;
                    case 2:
                        Main_Menuitems.friends = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends, 0);
                        break;
                    case 3:
                        Main_Menuitems.messages_in = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_in, 0);
                        break;
                    case 4:
                        Main_Menuitems.messages_out = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_out, 0);
                        break;
                    case 5:
                        Main_Menuitems.status = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.status, 0);
                        break;
                    case 6:
                        Main_Menuitems.settings_common = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.settings_common, 0);
                        break;
                    case 7:
                        Main_Menuitems.messages_reply_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_reply_message, 0);
                        break;
                    case 8:
                        Main_Menuitems.messages_new_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_new_message, 0);
                        break;
                    case 9:
                        Main_Menuitems.friends_online = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_online, 0);
                        break;
                    case 10:
                        Main_Menuitems.friends_mutual = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_mutual, 0);
                        break;
                    case 11:
                        Main_Menuitems.friends_new = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_new, 0);
                        break;
                }

                menuItem.MenuItems.Clear();
                menuItem.MenuItems.Add(this.MenuItem_friends_refresh);
                menuItem.MenuItems.Add(this.MenuItem_friends_all_online);
                menuItem.MenuItems.Add(this.MenuItem_friends_send_message);
                menuItem.MenuItems.Add(this.MenuItem_friends_get_contacts);
                menuItem.MenuItems.Add(this.MenuItem_friends_delete_contact);

                Main_Menuitems.tag = 2;
            }
        }




        private void MenuItem_friends_all_online_Click(object sender, EventArgs e)
        {
            contextMenu_friends_all_online.Checked = (contextMenu_friends_all_online.Checked) ? false : true;
        }

        private void MenuItem_friends_delete_contact_Click(object sender, EventArgs e)
        {
            if (listBox_friends_list.SelectedIndex >= 0 && listBox_friends_list.Items[listBox_friends_list.SelectedIndex].ToString() != "")
            {
                listBox_friends_list.Items.Remove(listBox_friends_list.SelectedItem);
            }
            else
            {
                AddToLog("Не выбран контакт", true);
            }
        }

        private void MenuItem_friends_refresh_Click(object sender, EventArgs e)
        {
            ThreadFriends_list_api api;
            if (MenuItem_friends_all_online.Checked)
            {
                api = new ThreadFriends_list_api("friends_online", this);
            }
            else
            {
                api = new ThreadFriends_list_api("friends", this);
            }

            Threads.status_thread = new Thread(new ThreadStart(api.go));
            Threads.status_thread.Name = "friends";
            Threads.status_thread.Start();
        }

        private void MenuItem_friends_contact_Click(object sender, EventArgs e)
        {

        }

        private void MenuItem_friends_send_message_Click(object sender, EventArgs e)
        {
            if (listBox_friends_list.SelectedIndex >= 0 && listBox_friends_list.Items[listBox_friends_list.SelectedIndex].ToString() != "")
            {
                panel1_send_message_tofriend.BringToFront();
                if (Main_Menuitems.tag != 1)
                {
                    switch (Main_Menuitems.tag)
                    {
                        case 1:
                            Main_Menuitems.friends_send_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.friends_send_message, 0);
                            break;
                        case 2:
                            Main_Menuitems.friends = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.friends, 0);
                            break;
                        case 3:
                            Main_Menuitems.messages_in = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_in, 0);
                            break;
                        case 4:
                            Main_Menuitems.messages_out = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_out, 0);
                            break;
                        case 5:
                            Main_Menuitems.status = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.status, 0);
                            break;
                        case 6:
                            Main_Menuitems.settings_common = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.settings_common, 0);
                            break;
                        case 7:
                            Main_Menuitems.messages_reply_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_reply_message, 0);
                            break;
                        case 8:
                            Main_Menuitems.messages_new_message = new MenuItem[menuItem.MenuItems.Count];
                            menuItem.MenuItems.CopyTo(Main_Menuitems.messages_new_message, 0);
                            break;
                    }

                    menuItem.MenuItems.Clear();
                    menuItem.MenuItems.Add(this.MenuItem_messages_send_message);
                    menuItem.MenuItems.Add(this.MenuItem_messages_cancel_send_message);
                    Main_Menuitems.tag = 1;
                    Main_Friends_API.friend_list_index = listBox_friends_list.SelectedIndex;
                    label_friend_info.Text = listBox_friends_list.Items[listBox_friends_list.SelectedIndex].ToString();
                    SipShowIM(SIPF_ON);
                }
            }
            else
            {
                AddToLog("Не выбран контакт для отправки сообщения", true);
            }
        }

        private void MenuItem_auth_Click(object sender, EventArgs e)
        {
            if (howitworks.auth_status == false)
            {
                Threads.status_thread = new Thread(new ThreadStart(Auth_userapi));
            }
            else
            {
                Threads.status_thread = new Thread(new ThreadStart(Logout_userapi));
            }
            Threads.status_thread.Name = "auth";
            Threads.status_thread.Start();
        }

        private void MenuItem_restore_Click(object sender, EventArgs e)
        {
            Threads.status_thread = new Thread(new ThreadStart(Restore_session_userapi));
            Threads.status_thread.Name = "restore_session";
            Threads.status_thread.Start();
        }
        
        private void MenuItem_clear_status_Click(object sender, EventArgs e)
        {
            Threads.status_thread = new Thread(new ThreadStart(Clear_status_userapi));
            Threads.status_thread.Name = "clear_status";
            Threads.status_thread.Start();
        }

        private void MenuItem_history_status_Click(object sender, EventArgs e)
        {
            Threads.status_thread = new Thread(new ThreadStart(History_status_userapi));
            Threads.status_thread.Name = "history_status";
            Threads.status_thread.Start();
        }

        private void ContextMenu_send_message_send_Click(object sender, EventArgs e)
        {
            string act = "add_message";
            ThreadFriends_send_message_api api = new ThreadFriends_send_message_api(Main_Friends_API.id[Main_Friends_API.friend_list_index], txt_send_message_tofriend.Text, act, this);
            Threads.messages_thread = new Thread(new ThreadStart(api.go));
            Threads.messages_thread.Name = "send_message_tofriend";
            Threads.messages_thread.Start();

            if (Main_Menuitems.tag != 2)
            {
                switch (Main_Menuitems.tag)
                {
                    case 1:
                        Main_Menuitems.friends_send_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_send_message, 0);
                        break;
                    case 2:
                        Main_Menuitems.friends = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends, 0);
                        break;
                    case 3:
                        Main_Menuitems.messages_in = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_in, 0);
                        break;
                    case 4:
                        Main_Menuitems.messages_out = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_out, 0);
                        break;
                    case 5:
                        Main_Menuitems.status = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.status, 0);
                        break;
                    case 6:
                        Main_Menuitems.settings_common = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.settings_common, 0);
                        break;
                    case 7:
                        Main_Menuitems.messages_reply_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_reply_message, 0);
                        break;
                    case 8:
                        Main_Menuitems.messages_new_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_new_message, 0);
                        break;
                    case 9:
                        Main_Menuitems.friends_online = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_online, 0);
                        break;
                    case 10:
                        Main_Menuitems.friends_mutual = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_mutual, 0);
                        break;
                    case 11:
                        Main_Menuitems.friends_new = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_new, 0);
                        break;
                }

                menuItem.MenuItems.Clear();
                menuItem.MenuItems.Add(this.MenuItem_friends_refresh);
                menuItem.MenuItems.Add(this.MenuItem_friends_all_online);
                menuItem.MenuItems.Add(this.MenuItem_friends_send_message);
                menuItem.MenuItems.Add(this.MenuItem_friends_get_contacts);
                menuItem.MenuItems.Add(this.MenuItem_friends_delete_contact);

                Main_Menuitems.tag = 2;
            }
        }

        private void ContextMenu_send_message_cancel_Click(object sender, EventArgs e)
        {
            panel1_send_message_tofriend.SendToBack();
            if (Main_Menuitems.tag != 2)
            {
                switch (Main_Menuitems.tag)
                {
                    case 1:
                        Main_Menuitems.friends_send_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_send_message, 0);
                        break;
                    case 2:
                        Main_Menuitems.friends = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends, 0);
                        break;
                    case 3:
                        Main_Menuitems.messages_in = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_in, 0);
                        break;
                    case 4:
                        Main_Menuitems.messages_out = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_out, 0);
                        break;
                    case 5:
                        Main_Menuitems.status = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.status, 0);
                        break;
                    case 6:
                        Main_Menuitems.settings_common = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.settings_common, 0);
                        break;
                    case 7:
                        Main_Menuitems.messages_reply_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_reply_message, 0);
                        break;
                    case 8:
                        Main_Menuitems.messages_new_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_new_message, 0);
                        break;
                    case 9:
                        Main_Menuitems.friends_online = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_online, 0);
                        break;
                    case 10:
                        Main_Menuitems.friends_mutual = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_mutual, 0);
                        break;
                    case 11:
                        Main_Menuitems.friends_new = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_new, 0);
                        break;
                }

                menuItem.MenuItems.Clear();
                menuItem.MenuItems.Add(this.MenuItem_friends_refresh);
                menuItem.MenuItems.Add(this.MenuItem_friends_all_online);
                menuItem.MenuItems.Add(this.MenuItem_friends_send_message);
                menuItem.MenuItems.Add(this.MenuItem_friends_get_contacts);
                menuItem.MenuItems.Add(this.MenuItem_friends_delete_contact);

                Main_Menuitems.tag = 2;
            }
        }

        private void menuItem_messages_in_Click(object sender, EventArgs e)
        {
            panel3_in_messages.BringToFront();

            if (Main_Menuitems.tag != 3)
            {
                switch (Main_Menuitems.tag)
                {
                    case 1:
                        Main_Menuitems.friends_send_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_send_message, 0);
                        break;
                    case 2:
                        Main_Menuitems.friends = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends, 0);
                        break;
                    case 3:
                        Main_Menuitems.messages_in = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_in, 0);
                        break;
                    case 4:
                        Main_Menuitems.messages_out = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_out, 0);
                        break;
                    case 5:
                        Main_Menuitems.status = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.status, 0);
                        break;
                    case 6:
                        Main_Menuitems.settings_common = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.settings_common, 0);
                        break;
                    case 7:
                        Main_Menuitems.messages_reply_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_reply_message, 0);
                        break;
                    case 8:
                        Main_Menuitems.messages_new_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_new_message, 0);
                        break;
                    case 9:
                        Main_Menuitems.friends_online = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_online, 0);
                        break;
                    case 10:
                        Main_Menuitems.friends_mutual = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_mutual, 0);
                        break;
                    case 11:
                        Main_Menuitems.friends_new = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_new, 0);
                        break;
                }

                menuItem.MenuItems.Clear();
                menuItem.MenuItems.Add(this.MenuItem_messages_in_new_message);
                menuItem.MenuItems.Add(this.MenuItem_messages_in_receive);
                menuItem.MenuItems.Add(this.MenuItem_messages_in_reply);
                menuItem.MenuItems.Add(this.MenuItem_messages_in_delete);

                Main_Menuitems.tag = 3;
            }
        }

        private void menuItem_messages_out_Click(object sender, EventArgs e)
        {
            panel4_out_messages.BringToFront();

            if (Main_Menuitems.tag != 4)
            {
                switch (Main_Menuitems.tag)
                {
                    case 1:
                        Main_Menuitems.friends_send_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_send_message, 0);
                        break;
                    case 2:
                        Main_Menuitems.friends = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends, 0);
                        break;
                    case 3:
                        Main_Menuitems.messages_in = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_in, 0);
                        break;
                    case 4:
                        Main_Menuitems.messages_out = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_out, 0);
                        break;
                    case 5:
                        Main_Menuitems.status = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.status, 0);
                        break;
                    case 6:
                        Main_Menuitems.settings_common = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.settings_common, 0);
                        break;
                    case 7:
                        Main_Menuitems.messages_reply_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_reply_message, 0);
                        break;
                    case 8:
                        Main_Menuitems.messages_new_message = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.messages_new_message, 0);
                        break;
                    case 9:
                        Main_Menuitems.friends_online = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_online, 0);
                        break;
                    case 10:
                        Main_Menuitems.friends_mutual = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_mutual, 0);
                        break;
                    case 11:
                        Main_Menuitems.friends_new = new MenuItem[menuItem.MenuItems.Count];
                        menuItem.MenuItems.CopyTo(Main_Menuitems.friends_new, 0);
                        break;
                }

                menuItem.MenuItems.Clear();
                menuItem.MenuItems.Add(this.MenuItem_messages_out_new_message);
                menuItem.MenuItems.Add(this.MenuItem_messages_out_receive);
                menuItem.MenuItems.Add(this.MenuItem_messages_out_reply);
                menuItem.MenuItems.Add(this.MenuItem_messages_out_delete);

                Main_Menuitems.tag = 4;
            }
        }

        private void MenuItem_messages_in_receive_Click(object sender, EventArgs e)
        {
            ThreadMessages_list_api api = new ThreadMessages_list_api("inbox", this);
            Threads.status_thread = new Thread(new ThreadStart(api.go));
            Threads.status_thread.Name = "messages";
            Threads.status_thread.Start();
        }

        private void MenuItem_messages_out_receive_Click(object sender, EventArgs e)
        {
            ThreadMessages_list_api api = new ThreadMessages_list_api("outbox", this);
            Threads.status_thread = new Thread(new ThreadStart(api.go));
            Threads.status_thread.Name = "messages";
            Threads.status_thread.Start();
        }

        private void menuItem_friend_new_Click(object sender, EventArgs e)
        {
            ThreadFriends_list_api api = new ThreadFriends_list_api("friends_new", this);
            Threads.status_thread = new Thread(new ThreadStart(api.go));
            Threads.status_thread.Name = "friends";
            Threads.status_thread.Start();
        }

        private void Main_Form_Activated(object sender, EventArgs e)
        {
            timer.Enabled = true;
        }

        private void Main_Form_Deactivate(object sender, EventArgs e)
        {
            timer.Enabled = false;
        }

        private void MenuItem_friends_get_avatar_Click(object sender, EventArgs e)
        {

        }
    }
}